<?php
class channelModel extends RPHP_Model
{

    protected $_auth = null;

    //检查权限
    public function checkPriv($pv, $return = true, $menu = true)
    {
        $auth = $this->auth->CheckPriv($pv, $return, $menu);
        if ($return) {
            $this->_auth = $auth;
        }

        return $auth;
    }

    //保存规格排序
    public function saveSpecSort($da)
    {
        $code = 900;
        if ($da['value'] != "") {
            $ids = json_decode($da['value'], true);
    
            foreach ($ids as $k => $r) {
                $sql = "UPDATE {$this->_prefix['primary']}goods_spec SET `sort`=" . $k . " WHERE `caid`=" . intval($r['id']);
                $this->sql($sql);
            }
            $code = 200;
        }
        return $code;
    }

    //规格属性重组
    public function getGoodsStockInfoV2($goods_id)
    {
        $item = $this->table("goods_affi_spec")->findAllBySql("`goods_id`=".$goods_id,'spec_id');
        if ($item) {
            $spec_id_str = "";
            foreach ($item as $key => $value) {
                $spec_id_str .= $value['spec_id'].',';
            }
        }
        $spec_id_str = rtrim($spec_id_str,',');
        $spec_id_arr = array_unique(explode(',', $spec_id_str));
        if($spec_id_arr){
            $goods_spec_pic = $this->table('goods_affi_spec_pic')->findAllBySql(" `spec_id` IN (".implode(',', $spec_id_arr).")",'pic_path,spec_id');
            if($goods_spec_pic){
                 foreach($goods_spec_pic as $pic){
                     $spec_pics[$pic['spec_id']] = $pic['pic_path'];

                 }
            }
            $goods_spec = $this->table('goods_spec')->findAllBySql("`stat`=1 AND `caid` IN (".implode(',', $spec_id_arr).")",'fucaid,caid,name');
            if($goods_spec){
                $arr = [];
                $fcaid = [];
                $spe_pic = [];
                foreach($goods_spec as $v){
                    $v['pic'] = $spec_pics[$v['caid']];
                    $fcaid[$v['fucaid']] =$v['fucaid'];
                    $arr[$v['fucaid']][] = $v;
                }
            }
            if($fcaid){
                $fgoods_spec = $this->table('goods_spec')->findAllBySql("`stat`=1 AND `caid` IN (".implode(',', $fcaid).")",'fucaid,caid,name');
                if($fgoods_spec){
                    foreach($fgoods_spec as $spc){
                        $fspecs[$spc['caid']] = $spc;

                    }


                }
            }
            $data = [];
            $i=0;
            if($arr){
                foreach($arr as $k=>$v){



                    $data[$i] =  $fspecs[$k];
                    $data[$i]['p'] =  $v;
                    $i++;

                }
            }
        }

         return $data;
    }



    //删除规格属性
    public function deleteSpec($caid)
    {
        $sql = "UPDATE {$this->_prefix['primary']}goods_spec SET `stat` = 3,`last_edit`=".time()." WHERE `caid`=" . intval($caid) . "   LIMIT 1";
        return $this->sql($sql);
    }
    //获取所有规格
    public function getSpec($caid = 0, $isfucaid = false,$cate_id=0)
    {
        
        if($cate_id){
            
            $tsql = " AND `cate_id`=" . intval($cate_id);
            if ($isfucaid) {
                $tsql = " AND `fucaid`=" . intval($caid);
            } elseif ($caid > 0) {
                $tsql = " AND `caid`=" . intval($caid);
            }
        
            
        
            $sql = "SELECT * FROM {$this->_prefix['primary']}goods_spec WHERE  `stat`=1  " . $tsql . " ORDER BY `fucaid` ASC,`sort` ASC,`stat` ASC,`caid` ASC ";
        
            if ($caid > 0 && !$isfucaid) {
                $newdata = $this->db->getrow($sql);
            } else {
                $data = $this->sql($sql);
                if ($data) {
                    if ($isfucaid) {
                        $newdata = $data;
                    } else {
                        foreach ($data as $r) {
                            $newdata[$r['fucaid']][$r['caid']] = $r;
                        }
                    }
                }
            }
        }
        return $newdata;
    }

    public function getGoodsSpecs($caid = 0, $isfucaid = false,$cate_id=0,$goods_id=0)
    {
       
        if($cate_id){
           
            $sql = "SELECT COUNT(*) FROM {$this->_prefix['primary']}goods_spec WHERE  `stat`=1  AND `cate_id`=".$cate_id;
            $cate_num = $this->db->getone($sql);
           
            if(!$cate_num){
                
                $sql = "SELECT * FROM {$this->_prefix['primary']}goods_category WHERE  `stat`=1 AND  `caid`=".$cate_id;
                $cate_info = $this->db->getrow($sql);
                if($cate_info['fucaid'] !=0){
                    $sql = "SELECT `caid` FROM {$this->_prefix['primary']}goods_category WHERE  `stat`=1 AND `caid`=".$cate_info['fucaid'];
                    $pid = $this->db->getone($sql);
                    $cate_id = $pid;
                    
                }
            }
           
            $tsql = " AND `cate_id`=" . intval($cate_id);
            if ($isfucaid) {
                $tsql = " AND `fucaid`=" . intval($caid);
            } elseif ($caid > 0) {
                $tsql = " AND `caid`=" . intval($caid);
            }
        
        
       
            $sql = "SELECT * FROM {$this->_prefix['primary']}goods_spec WHERE  `stat`=1  " . $tsql . " ORDER BY `fucaid` ASC,`sort` ASC,`stat` ASC,`caid` ASC ";
        
            if ($caid > 0 && !$isfucaid) {
                $newdata = $this->db->getrow($sql);
            } else {
                $data = $this->sql($sql);
               // print_r($data);print_r($tsql);die();
                if ($data) {
                    if ($isfucaid) {
                        $newdata = $data;
                    } else {
                        foreach ($data as $r) {
                            if($goods_id>0){
                                $r['pic_path'] = "";
                                $r['pic_id'] = 0;
                                 $sql = "SELECT `pic_path`,`id` FROM {$this->_prefix['primary']}goods_affi_spec_pic WHERE `goods_id`=" . intval($goods_id) . "  AND `spec_id`=".$r['caid'];
                                 $pic_data  = $this->db->getrow($sql);
                                 if($pic_data){
                                     $r['pic_id'] = $pic_data['id'];
                                     
                                     $r['pic_path'] = $pic_data['pic_path'];
                                 }
                                
                            }
                            $newdata[$r['fucaid']][$r['caid']] = $r;
                        }
                    }
                }
            }
        }
       //print_r($newdata);die;
        return $newdata;
        
    }

    public function delSpecPic($id=0)
    {

        $id = intval($id);
        if($id){
            $f['update_time'] = time();
            $f['pic_path'] = "";

            $res = $this->table("goods_affi_spec_pic")->update($f,"`id`=".$id);
            if($res){

                return array("code"=>200,"msg"=>"删除成功");
            }


        }

        return array("code"=>900,"msg"=>"删除失败");
    }

    //上传图片
    public function saveSpecPic($da=array(),$file,$goods_id=0)
    {
        $data = array();
        $code = 900;
       
       
        if(!empty($file['tmp_name']) && $goods_id>0 && !empty($da['spec_id'])){
           
            foreach($file['tmp_name'] as $k=>$v){
                if ($v != "" && $file['size'][$k] > 0) {
                
                    if (in_array($file['type'][$k], $this->c['upload']['mime'])) {
                
                        if ($file['size'][$k] <= $this->c['upload']['size']) {
                            $format = $this->upload->rf($file['name'][$k]);
                
                            if (in_array($format, $this->c['upload']['fm'])) {
                
                                //创建目录
                                $dir['date'] = $this->c['upload']['dir'] . date("Ymd", $_SERVER['REQUEST_TIME']);
                                if (!file_exists($dir['date'])) {
                                    mkdir($dir['date']);
                                }
                
                                $dir['hour'] = $dir['date'] . DIRECTORY_SEPARATOR . date("H", $_SERVER['REQUEST_TIME']);
                                if (!file_exists($dir['hour'])) {
                                    mkdir($dir['hour']);
                                }
                
                                $dir['minute'] = $dir['hour'] . DIRECTORY_SEPARATOR . date("i", $_SERVER['REQUEST_TIME']);
                                if (!file_exists($dir['minute'])) {
                                    mkdir($dir['minute']);
                                }
                
                                if (file_exists($dir['minute'])) {
                
                                    //移动文件
                                    $filename = md5($v . $_SERVER['REQUEST_TIME']) . "." . $format;
                
                                    $filepath = $dir['minute'] . DIRECTORY_SEPARATOR . $filename;
                
                                    if (move_uploaded_file($v, $filepath)) {
                                        $docid = $this->saveDocument($file['name'][$k], $filename, $file['size'][$k], $format, $_SERVER['REQUEST_TIME']);
                
                                        if ($docid > 0) {
                
                                           //查出是否有创建规格图片
                                             $sql = "SELECT `id` FROM {$this->_prefix['primary']}goods_affi_spec_pic WHERE `goods_id`=" . $goods_id . "  AND `spec_id`=".$da['spec_id'][$k];
                                             $id  = $this->db->getone($sql);
                                            
                                           
                                            $pic_path   = $this->c['doc_host'] . date("Ymd", $_SERVER['REQUEST_TIME']) . "/" . date("H", $_SERVER['REQUEST_TIME']) . "/" . date("i", $_SERVER['REQUEST_TIME']) . "/" . $filename;
                                            if($id>0){
                                                $sql = "UPDATE {$this->_prefix['primary']}goods_affi_spec_pic SET `pic_path`='" . $pic_path . "',`pic`=" . $docid . ",`update_time`=" . $_SERVER['REQUEST_TIME']  . " WHERE `id`=" . $id;
                                                $rd  = $this->sql($sql);
                                                if($rd){
                                                     
                                                    $code = 200;
                                                }
                                            }else{
                                                $sql = "INSERT INTO {$this->_prefix['primary']}goods_affi_spec_pic
                                                (`pic`,`pic_path`,`spec_id`,`goods_id`,`create_time`) VALUES
                                                (" . $docid . ",'" . $pic_path . "'," . $da['spec_id'][$k] . "," . $goods_id . "," . $_SERVER['REQUEST_TIME']  . ")";
                                                $rd = $this->sql($sql);
                                                if($rd){
                                                     
                                                    $code = 200;
                                                }
                                                
                                            }
                                        } else {
                                            $code = 701;
                                            @unlink($filepath);
                                        }
                                    } else {
                                        $code = 705;
                                    }
                
                                } else {
                                    $code = 706;
                                }
                
                            } else {
                                $code = 703;
                            }
                
                          
                
                        } else {
                            $code = 704;
                        }
                
                    } else {
                        $code = 703;
                    }
                
                }
                
            }
            
        }
        return $code;
 
    }

    //保存规格
    public function saveSpec($da, $caid = 0,$cate_id=0)
    {
    
        $code   = 900;
        $name   = addslashes(htmlspecialchars(trim($da['name'])));
        $stat   = intval($da['stat']);
        $fucaid = intval($da['fucaid']);
    
        //修改
        if ($caid > 0 && $cate_id >0) {
    
            $sql = "SELECT * FROM {$this->_prefix['primary']}goods_spec WHERE `caid`=" . intval($caid) . "  AND `stat`<3";
            $rs  = $this->db->getrow($sql);
    
            if ($rs) {
                 
                $sql = "UPDATE {$this->_prefix['primary']}goods_spec SET `stat`=" . $stat . ",`fucaid`=" . $fucaid . ",`name`='" . $name . "',`last_staffid`=3,`last_staffedit`=" . $_SERVER['REQUEST_TIME']  . " WHERE `caid`=" . $rs['caid'];
                $rd  = $this->sql($sql);
                if ($rd > 0) {
                    $code = 200;
                } else {
                    $code = 403;
                }
    
            } else {
                $code = 404;
            }
    
        }
        //新增
        else {
            if ($da['name'] != "") {
                
                $sql = "INSERT INTO {$this->_prefix['primary']}goods_spec
                (`cate_id`,`name`,`fucaid`,`stat`,`last_staffid`,`last_staffedit`) VALUES
                (" . $cate_id . ",'" . $name . "'," . $fucaid . "," . $stat . ",3," . $_SERVER['REQUEST_TIME']  . ")";
                $rd = $this->sql($sql);
    
                if ($rd > 0) {
                    $code = 200;
                } else {
                    $code = 403;
                }
    
            }
        }
        return $code;
    
    }
    
    //获取商品设置的全部规格信息
    public function getGoodsStockList($goods_id)
    {
        $arr = array();
        $sql = "SELECT * FROM {$this->_prefix['primary']}goods_affi_spec WHERE `goods_id`=" . intval($goods_id);
        $rs  = $this->sql($sql);
        if($rs){
            $stock_total = 0;
            foreach($rs as $v){
                $stock_total +=$v['goods_number'];
                
            }
            $arr['data'] = $rs;
            $arr['stock_total'] = $stock_total;
        }
        
        return $arr;
        
    }
    //设置商品规格
    public function setGoodsSpec($da)
    {
        $arr['code'] = 900;
        $arr['msg'] = "设置失败";
        
        $goods_id = intval($da['goods_id']);
        $spec_ids = $da['spec_ids'];
        $goods_price = $da['goods_price'];
        $goods_number = $da['goods_number'];
        $spec_names = $da['spec_names'];
        $goods_sn = $da['goods_sn'];
        if(!empty($spec_ids) && !empty($goods_price) && !empty($goods_number)  && $goods_id && !empty($spec_names)){
            $this->db->begin();
            $done = true;
            foreach($spec_ids as $k=>$v){
               
                 $spec_id = '';
                if($v !='' && $goods_price[$k]>0 && $goods_number[$k]>0 && $spec_names[$k] !=''){

                     $spec_array = explode(',',$v);
                      sort($spec_array);
                      $spec_md5 = md5(implode(',',$spec_array));
                 
                    $sql = "INSERT INTO {$this->_prefix['primary']}goods_affi_spec
                    (`goods_id`,`spec_id`,`spec_md5`,`goods_number`,`goods_price`,`spec_name`,`goods_sn`,`create_time`) VALUES
                    (".$goods_id.",'" . $v . "','" . $spec_md5 . "'," . $goods_number[$k] . ",'" . $goods_price[$k] . "','" . $spec_names[$k] . "','" . $goods_sn[$k] . "'," . $_SERVER['REQUEST_TIME'] .")";
                    $rd = $this->sql($sql);
                    if(!$rd){
                        
                        $done = false;
                    }
                    
                }
               
                
            }
            
            if ($done) {
                $this->db->commit();
                $arr['code'] = 200;
                $arr['msg'] = "设置成功";
                $arr['ref'] = $da['ref'];
            } else {
                $this->db->rollback();
            }
            
        }
       
        return $arr;
        
    }
    //已选商品属性及图片
    public function getGoodsSpecPic($goods_id)
    {
        $newdata = array();
        if($goods_id){
            $sql = "SELECT * FROM {$this->_prefix['primary']}goods_affi_spec WHERE `goods_id`=" . $goods_id;
            $rs  = $this->sql($sql);
            if($rs){
                $spec_ids= "";
                foreach($rs as $k=>$v){
                    
                    if($v['spec_id'] !=""){
                        $spec_ids .= empty($spec_ids)?$v['spec_id']:",".$v['spec_id'];
                        
                    }
                    
                }
                
                $spec_array = array_unique(explode(",",$spec_ids));
                $where = " AND `caid` IN (" . implode(",", array_unique($spec_array)) . ")";                 //查出规格所有的属性
                $sql = "SELECT * FROM {$this->_prefix['primary']}goods_spec WHERE `fucaid` <> 0 AND `stat`=1".$where;
                $specs  = $this->sql($sql);
                if($specs){
                    $pid = array();
                    foreach ($specs as $r) {
                        if(!in_array($r['fucaid'],$pid)){
                            $pid[] = $r['fucaid'];
                            $sql = "SELECT * FROM {$this->_prefix['primary']}goods_spec WHERE `caid`=".$r['fucaid'];
                            $pspecs  = $this->db->getrow($sql);
                            $newdata[0][$r['fucaid']] = $pspecs;
                        }
                        $r['pic_path'] = "";
                        $sql = "SELECT `pic_path` FROM {$this->_prefix['primary']}goods_affi_spec_pic WHERE `goods_id`=" . intval($goods_id) . "  AND `spec_id`=".$r['caid'];
                        $pic_path  = $this->db->getone($sql);
                        if($pic_path){
                            $r['pic_path'] = $pic_path;
                            
                        }
                        $newdata[$r['fucaid']][$r['caid']] = $r;
                    }
                    
              
                }

            }
            
        }
        
        return $newdata;
        
    }
    
    //修改商品规格库存及会员价
    public function setSpecStock($da)
    {
        $arr['code'] = 900;
        $arr['msg'] = "修改失败";
        $stock_id = intval($da['stock_id']);
        $type = intval($da['type']);
        
        if($type ==1){
            $keyword = intval($da['keyword']);
            $set = "`goods_number`=".$keyword.",`update_time`=".time();

        }else if($type ==2){
            $keyword = addslashes(htmlspecialchars(trim($da['keyword'])));
            $set = "`goods_sn`='".$keyword."',`update_time`=".time();

        }else{
            $keyword = number_format($da['keyword'], 2, '.', '');
            $set = "`goods_price`='".$keyword."',`update_time`=".time();

        }
//echo $set;die;
      //  if($keyword >0){
            
            $sql = "UPDATE {$this->_prefix['primary']}goods_affi_spec SET " . $set . " WHERE `stock_id`=" . $stock_id;
            $rs = $this->sql($sql);
            
            if($rs){
                
                $arr['code'] = 200;
                $arr['msg'] = "修改成功";
            }
            
       // }
        return $arr;
        
    }


    //修改商品规格库存及会员价
    public function saveSpecStat($da)
    {
        $arr['code'] = 900;
        $arr['msg'] = "修改失败";
        $stock_id = intval($da['stock_id']);
        $spec = $this->table('goods_affi_spec')->findBySql("`stock_id`=".$stock_id);

        if($spec){
            $stat = 1;
            if($spec['stat']==1){
                $stat = 2;

            }
            $sql = "UPDATE {$this->_prefix['primary']}goods_affi_spec SET `stat`=".$stat." WHERE `stock_id`=" . $stock_id;
            $rs = $this->sql($sql);

            if($rs){

                $arr['code'] = 200;
                $arr['msg'] = "修改成功";
            }


        }

        // }
        return $arr;

    }

    //获取关键词表数据
    public function getKeywordsList($para, $page, $pagesize = 20)
    {
        $where .= " 1=1 ";

        if ($para) {
            if ($para['keyword'] != '') {
                $uid = $this->table('member_account')->findOneBySql("`realname` LIKE '%".$para['keyword']."%'",'uid');
                $where .= "AND (`uid` = '" . $para['keyword'] . "' OR `uid` = '" . $uid . "')";

            }

            if ($para['start_time'] != '') {

                $where .= " AND `create_time` >" . $para['start_time'];
                $para['start_time'] = date("Y-m-d H:i:s", $para['start_time']);
            }

            if ($para['end_time'] != '') {
                $where .= "   AND `create_time` <=" . $para['end_time'];
                $para['end_time'] = date("Y-m-d H:i:s", $para['end_time']);
            }

        }
        
        $sql = "SELECT COUNT(*) AS `cnt` FROM {$this->_prefix['primary']}keywords_log WHERE " . $where;
        $cnt = $this->sql($sql);

        if ($cnt[0]['cnt'] > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "`create_time` DESC,`keywords_id` DESC";

            $sql = "SELECT * FROM {$this->_prefix['primary']}keywords_log WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;
            $rs  = $this->sql($sql);
            if ($rs) {
                foreach ($rs as $key => $value) {
                    $rs[$key]['realname'] = $this->table('member_account')->findOneBySql('`uid`='.$value['uid'],'realname');
                }
            }

        }
        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt[0]['cnt'] / $pagesize),
            'count'   => $cnt[0]['cnt'],
            'data'    => $rs,
            'para'    => $para,
        );

    }

    public function getGoodsSearch()
    {
        $keyword = input_str('keyword');
        $data    = [];

        if ($keyword) {
            if (is_numeric($keyword)) {

                $where = "`goods_id` =" . $keyword;
            } else {

                $where = "`goods_name` LIKE '%" . $keyword . "%'";
            }

            $data = $this->table('goods_data')->findAllBySql("`is_on_sale`=1 AND `is_delete`=0 AND " . $where, "`goods_name`,`goods_id`,`shop_price`");

        }
        return $data;
    }

    public function getGoodsDetail()
    {
        $goods_id = input_str('goods_id');
        $data     = $this->table('goods_data')->findBySql("`is_on_sale`=1 AND `is_delete`=0 AND `goods_id`=" . $goods_id, "`goods_name`,`goods_id`,`shop_price`");
        return $data;
    }

    //今日特卖详情
    public function getSpecialDetail($id)
    {
        $data = $this->table("today_special")->findByPk($id);
        if ($data) {
            $goods = $this->table('goods_data')->findAllBySql("`is_on_sale`=1 AND `is_delete`=0 AND `goods_id` IN (" . $data['goods_ids'] . ")", "`goods_name`,`goods_id`,`shop_price`");

            $data['goods'] = $goods;
        }
        return $data;
    }

    //今日特卖保存功能
    public function saveSpecial()
    {
        $ids        = input_str("ids");
        $start_time = strtotime($_POST['start_time']);
        $end_time   = strtotime($_POST['end_time']);
        $code       = 900;
        $id         = input_int("id");

        if ($ids && $start_time && $end_time) {
            $f['start_time'] = $start_time;
            $f['end_time']   = $end_time;
            $f['goods_ids']  = $ids;

            if ($end_time <= $start_time) {

                return "开始时间不能小于结束时间";
            }

            if ($id) {
                /* $special = $this->table("today_special")->findBySql("`id` <> ".$ids."  ORDER BY `create_time` desc");
                if($special){
                if($start_time <=$special['end_time']){
                return 41001;

                }

                }*/
                $f['update_time'] = time();

                $res = $this->table("today_special")->update($f, "`id`=" . $id);

            } else {

                /* $special = $this->table("today_special")->findBySql("1 ORDER BY `create_time` desc");
                if($special){
                if($start_time <=$special['end_time']){
                return 41001;

                }

                }*/
                $f['create_time'] = time();

                $res = $this->table("today_special")->insert($f);

            }

            if ($res) {

                $code = 200;
            }

        }

        return $code;

    }

    //今日特卖删除
    public function delSpecial()
    {
        $id          = input_int('id');
        $arr['code'] = 900;
        $arr['msg']  = "删除失败请重试！";
        $res         = $this->table('today_special')->delete("`id`=" . $id);
        if ($res) {

            $arr['code'] = 200;
            $arr['msg']  = "删除成功";
        }
        return $arr;
    }
    //今日特卖列表
    public function getTodaySpecical($para, $page, $pagesize = 20)
    {
        $where .= " 1=1 ";

        if ($para) {

            if ($para['start_time'] != '') {

                $where .= " AND `start_time` >" . $para['start_time'];
                $para['start_time'] = date("Y-m-d H:i:s", $para['start_time']);
            }

            if ($para['end_time'] != '') {
                $where .= "   AND `saveCategory` <=" . $para['end_time'];
                $para['end_time'] = date("Y-m-d H:i:s", $para['end_time']);
            }

        }

        $sql = "SELECT COUNT(*) AS `cnt` FROM {$this->_prefix['primary']}today_special WHERE " . $where;
        $cnt = $this->sql($sql);
        if ($cnt[0]['cnt'] > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "`create_time` DESC,`id` DESC";

            $sql = "SELECT * FROM {$this->_prefix['primary']}today_special WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;
            $rs  = $this->sql($sql);

        }
        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt[0]['cnt'] / $pagesize),
            'count'   => $cnt[0]['cnt'],
            'data'    => $rs,
            'para'    => $para,
        );

    }

    //查找分类奖励配置信息
    public function getcateAwardDetail($caid)
    {
        $data = $this->table('goods_category')->findBySql("`fucaid` = 0 AND caid=" . $caid, 'award_json');
        $arr  = [];
        if ($data) {
            $arr = json_decode($data['award_json'], true);

        }
        return $arr;

    }

    //分类奖励配置操作
    public function saveCategoryAward($da)
    {
        $caid = intval($da['caid']);
        $code = 900;
        if ($caid) {
            $f['seft_money']       = number_format($da['seft_money'], 2, '.', '');
            $f['re_money']         = number_format($da['re_money'], 2, '.', '');
            $f['order_money']      = number_format($da['order_money'], 2, '.', '');
            $f['team_order_money'] = number_format($da['team_order_money'], 2, '.', '');
            $f['capping_money']    = number_format($da['capping_money'], 2, '.', '');
            $json                  = json_encode($f);

            $d['last_edit']  = time();
            $d['award_json'] = $json;

            $res = $this->table('goods_category')->update($d, "`fucaid` = 0 AND caid=" . $caid);
            if ($res) {

                $code = 200;
            }
        }
        return $code;

    }
    //修改商品销量
    public function saveSalesCount($da)
    {
        $code         = 900;
        $msg          = "修改销量失败";
        $sales_counts = intval($da['sales_count']);
        $sales_count  = empty($sales_counts) ? 0 : $sales_counts;

        if (intval($da['goods_id'])) {

            if (is_numeric($sales_count)) {
                $sql = "UPDATE {$this->_prefix['primary']}goods_data SET `sales_count`=" . $sales_count . " WHERE goods_id=" . intval($da['goods_id']);

                $rc = $this->sql($sql);
                if ($rc) {

                    $code = 200;
                    $msg  = "修改销量成功";
                }

            } else {
                $code = 902;
                $msg  = "输入必须为数字！";

            }

        } else {
            $code = 901;
            $msg  = "商品ID不存在！";
        }

        return array('code' => $code, "msg" => $msg);

    }
    //getdocument
    public function getDocs($docid)
    {
        if (is_array($docid)) {
            $where = " WHERE `docid` IN (" . implode(",", array_unique($docid)) . ")";
        } else {
            $where = " WHERE `docid`=" . intval($docid);
        }

        $sql = "SELECT `docid`,`filename`,`create_time` FROM {$this->_prefix['primary']}documents " . $where;
        $rs  = $this->sql($sql);
        if ($rs) {
            foreach ($rs as $r) {
                $doc[$r['docid']] = $this->c['doc_host'] . date("Ymd", $r['create_time']) . "/" . date("H", $r['create_time']) . "/" . date("i", $r['create_time']) . "/" . $r['filename'];

            }
            return $doc;
        } else {
            return false;
        }

    }

    public function UploadPic($files)
    {
        $code = 706;
        //创建目录
        $dir['date'] = $this->c['upload']['dir'] . date("Ymd", $_SERVER['REQUEST_TIME']);
        if (!file_exists($dir['date'])) {
            mkdir($dir['date']);
        }

        $dir['hour'] = $dir['date'] . DIRECTORY_SEPARATOR . date("H", $_SERVER['REQUEST_TIME']);
        if (!file_exists($dir['hour'])) {
            mkdir($dir['hour']);
        }

        $dir['minute'] = $dir['hour'] . DIRECTORY_SEPARATOR . date("i", $_SERVER['REQUEST_TIME']);
        if (!file_exists($dir['minute'])) {
            mkdir($dir['minute']);
        }

        if (file_exists($dir['minute'])) {

            $doc_host = $this->c['doc_host'] . date("Ymd", $_SERVER['REQUEST_TIME']) . "/" . date("H", $_SERVER['REQUEST_TIME']) . "/" . date("i", $_SERVER['REQUEST_TIME']) . "/";

            foreach ($files['tmp_name'] as $k => $r) {

                if ($r != "") {
                    if (in_array($files['type'][$k], $this->c['upload']['mime'])) {

                        if ($files['size'][$k] <= $this->c['upload']['size']) {

                            $format = explode(".", $files['name'][$k]);
                            $format = strtolower($format[count($format) - 1]);

                            if (in_array($format, $this->c['upload']['fm'])) {

                                $filename = md5($_SERVER['REQUEST_TIME'] . $files['tmp_name'][$k] . $files['name'][$k]) . "." . $format;
                                $path     = $dir['minute'] . "/" . $filename;
                                if (move_uploaded_file($r, $path)) {

                                    $this->saveDocument($files['name'][$k], $filename, $files['size'][$k], $format, $_SERVER['REQUEST_TIME']);

                                    $data[$k] = '"' . $doc_host . $filename . '"';

                                } else {
                                    $error[$k] = 705;
                                }

                            } else {
                                $error[$k] = 703;
                            }

                        } else {
                            $error[$k] = 704;
                        }

                    } else {
                        $error[$k] = 703;
                    }

                } else {
                    $error[$k] = 702;
                }

                @unlink($r);

            }

        }
        return array('code' => $code, 'data' => $data, 'error' => $error);

    }

    //获取单个商品
    public function getSingleGoods($goods_id)
    {

        $sql  = "SELECT * FROM {$this->_prefix['primary']}goods_data WHERE `goods_id`=" . intval($goods_id) . " AND `is_delete`=0 LIMIT 1";
        $data = $this->db->getrow($sql);
        if ($data) {
            $sql       = "SELECT `title` FROM {$this->_prefix['primary']}goods_relevance WHERE `id`=" . intval($data['relevance_id']);
            $rele_info = $this->db->getrow($sql);

            if (!empty($rele_info)) {

                $data['title'] = $rele_info['title'];
            }
            // 获取库存信息
            $data['goods_number'] = $this->db->getone("SELECT `number` FROM {$this->_prefix['primary']}goods_stock WHERE `goods_id`=" . $data['goods_id'] . "  LIMIT 1");
        }

        return $data;

    }

    //关联(搜索)
    public function getRlevances($da)
    {
        if (!empty($da['info'])) {
            $title = addslashes(htmlspecialchars(trim($da['info'])));
            $where = "status >0";
            $where .= " AND (`title` LIKE '%" . $title . "%')";
            $sql = "SELECT * FROM {$this->_prefix['primary']}goods_relevance WHERE " . $where;
            $rs  = $this->sql($sql);
            return $rs;
        }

    }
    //获得关联
    public function getRlevance()
    {
        $sql = "SELECT * FROM {$this->_prefix['primary']}goods_relevance WHERE status >0";
        $rs  = $this->sql($sql);
        return $rs;

    }
    //关联列表

    public function getRelevanceList($para, $page = 1, $pagesize = 10)
    {

        $where = "1=1";
        if ($para['keyword'] != '') {
            $where .= "AND `title` LIKE '%" . $para['keyword'] . "%'";
        }

        if (isset($para['status'])) {
            $where .= " AND `status`  = " . $para['status'];

        }

        $sql = "SELECT COUNT(*) AS `cnt` FROM {$this->_prefix['primary']}goods_relevance  WHERE " . $where;
        $cnt = $this->db->getone($sql);
        if ($cnt > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "`id` DESC";

            $sql = "SELECT * FROM {$this->_prefix['primary']}goods_relevance WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;
            $rs  = $this->sql($sql);
            foreach ($rs as &$val) {
                $val['goodsList'] = '';
                $sql              = "SELECT * FROM {$this->_prefix['primary']}goods_data WHERE `relevance_id`=" . $val['id'];
                $goodsList        = $this->sql($sql);
                if (!empty($goodsList)) {
                    $val['goodsList'] = $goodsList;

                }

            }

            return array(
                'page'    => $page,
                'maxpage' => ceil($cnt / $pagesize),
                'count'   => $cnt,
                'data'    => $rs,
                'para'    => $para,

            );
        }

    }

    public function getRelevancel($id)
    {
        $data = array();
        if ($id) {
            $sql  = "SELECT * FROM {$this->_prefix['primary']}goods_relevance WHERE `id`=" . $id;
            $data = $this->db->getrow($sql);

        }
        return $data;

    }

    public function delRele($id, $goods_id)
    {
        $code = 900;
        $msg  = "移除失败，ID不存在！";
        if ($id && $goods_id) {
            $this->db->begin();
            $rollback = false;
            $sql      = "UPDATE {$this->_prefix['primary']}goods_data SET `relevance_id`=0 WHERE goods_id=" . $goods_id;

            $rc = $this->sql($sql);

            if ($rc) {
                $sql  = "SELECT * FROM {$this->_prefix['primary']}goods_relevance WHERE `id`=" . $id;
                $rele = $this->db->getrow($sql);
                if ($rele) {
                    $goods_ids = trim(str_replace($goods_id, '', $rele['goods_ids']), ',');

                    $sql     = "UPDATE {$this->_prefix['primary']}goods_relevance SET `goods_ids`='" . $goods_ids . "' WHERE id=" . $id;
                    $rele_id = $this->sql($sql);
                    if ($rele_id) {
                        $rollback = true;
                        $code     = 200;
                        $msg      = "移除成功！";

                    } else {

                        $code = 201;
                        $msg  = "移除失败！";
                    }

                }

            } else {
                $code = 202;
                $msg  = "移除失败！！";
            }

            if ($rollback) {
                $this->db->commit();

            } else {

                $this->db->rollback();
            }
            $arr         = array();
            $arr['code'] = $code;
            $arr['msg']  = $msg;
            return $arr;
        }
    }

    //保存供应商信息
    public function saveRelevance($da, $id = 0)
    {
        $code = 900;
        if ($da) {
            $field['title']       = addslashes(htmlspecialchars(trim($da['title'])));
            $field['option_name'] = addslashes(htmlspecialchars(trim($da['option_name'])));
            $field['create_time'] = time();
            //修改
            if ($id > 0) {

                $field['status'] = intval($da['status']);
                //修改供应商信息
                $sql = "UPDATE {$this->_prefix['primary']}goods_relevance SET ";
                foreach ($field as $key => $value) {
                    $upsql[] = "`" . $key . "`='" . $value . "'";
                }
                $sql .= implode(",", $upsql) . " WHERE `id`=" . $id;
                $rcnum = $this->sql($sql);
                if ($rcnum) {
                    $code = 200;

                }

            }
            //新增
            else {

                foreach ($field as $key => $value) {
                    $keys[]   = "`" . $key . "`";
                    $values[] = "'" . $value . "'";
                }
                //插入供应商信息
                $sql = "INSERT INTO {$this->_prefix['primary']}goods_relevance (" . implode(",", $keys) . ") VALUES (" . implode(",", $values) . ")";
                $id  = $this->sql($sql);
                if ($id > 0) {
                    $code = 200;
                }

            }
        }
        return $code;
    }

    //渠道商品
    public function getChannelGoods($stat = "", $para, $page = 1, $pagesize = 10)
    {

        $where = " `is_delete`=0 AND `shopid`=1 "; //添加渠道商品供应店铺ID
        if ($para) {

            if ($para['caid'] != '') {

                $caids = $this->getSmlCate($para['caid']);
                if ($caids) {
                    $caids[] = $para['caid'];
                    $where .= " AND `caid` IN (" . implode(",", $caids) . ")";
                } else {
                    $where .= " AND `caid`=" . $para['caid'];
                }

            }

            if ($para['goods_type'] != '') {
                $where .= " AND `goods_type`=" . $para['goods_type'];
            }

            if ($para['supplier_id'] != '') {
                $where .= " AND `supplierid`=" . $para['supplier_id'];
            }

            if (isset($para['is_on_sale']) && $para['is_on_sale'] >= 0) {
                $where .= " AND `is_on_sale`=" . $para['is_on_sale'];
            }

            if (isset($para['can_separate']) && $para['can_separate'] >= 0) {
                $where .= " AND `can_separate`=" . $para['can_separate'];
            }

            if ($para['rec']) {
                switch ($para['rec']) {
                    case 1:
                        $where .= " AND `is_best`=1";
                        break;
                    case 2:
                        $where .= " AND `is_hot`=1";
                        break;
                    case 3:
                        $where .= " AND `is_new`=1";
                        break;
                    case 4:
                        $where .= " AND `is_promote`=1";
                        break;
                }
            }

            if ($para['keyword'] != '') {
                $where .= " AND (`goods_name` LIKE '%" . $para['keyword'] . "%' OR `goods_sn` LIKE '%" . $para['keyword'] . "%' OR `goods_barcode` LIKE '%" . $para['keyword'] . "%' OR `goods_id`= '" . $para['keyword'] . "')";
                // print_r($where);die;
            }

        }

        if ($stat == "warn") {
            $para['stat'] = "warn";
            $sql          = "SELECT COUNT(GAN.`goods_id`) AS `cnt` FROM {$this->_prefix['primary']}goods_data AS GD INNER JOIN {$this->_prefix['primary']}goods_stock AS GAN ON GD.`goods_id` = GAN.`goods_id` AND GD.`is_on_sale`=1 AND GD.`is_delete`=0 AND GD.`warn_number`>=GAN.`number`";
            $start        = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "GD.`add_time` DESC,GD.`goods_id` DESC";

            $rssql = "SELECT GD.`can_separate`,GD.`goods_id`,GD.`goods_sn`,GD.`goods_name`,GD.`goods_sku`,GD.`pic_docid`,GD.`thumb_docid`,GD.`shopid`,GD.`shop_price`,GD.`warn_number`,GD.`is_on_sale`,GD.`is_best`,GD.`is_hot`,GD.`is_new`,GD.`add_time`,GD.`goods_weight`,GD.`market_price`,GD.`relevance_id`,GD.`goods_type`,GD.`ximi_price`,GD.`is_free_shipping`,GD.`upgrade_goods` FROM {$this->_prefix['primary']}goods_data AS GD INNER JOIN {$this->_prefix['primary']}goods_stock AS GAN ON GD.`goods_id` = GAN.`goods_id` AND GD.`is_on_sale`=1 AND GD.`is_delete`=0 AND GD.`warn_number`>=GAN.`number` ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;
        } else {
            $sql   = "SELECT COUNT(`goods_id`) AS `cnt` FROM {$this->_prefix['primary']}goods_data WHERE " . $where;
            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "`add_time` DESC,`goods_id` DESC";

            $rssql = "SELECT `can_separate`,`goods_id`,`goods_sn`,`goods_name`,`goods_sku`,`pic_docid`,`thumb_docid`,`weight`,`shopid`,`shop_price`,`warn_number`,`is_on_sale`,`is_best`,`is_hot`,`is_new`,`add_time`,`goods_weight`,`market_price`,`purchase_price`,`caid`,`brand_id`,`supplierid`,`sales_count`,`relevance_id`,`goods_type`,`ximi_price`,`is_free_shipping`,`upgrade_goods` FROM {$this->_prefix['primary']}goods_data WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;
        }

        $cnt = $this->db->getone($sql);
        if ($cnt > 0) {

            $rs = $this->sql($rssql);

            $docid = array();
            if ($rs) {
                foreach ($rs as $k => $v) {

                    if ($v['pic_docid'] > 0) {
                        $docid[] = $v['pic_docid'];
                    }

                    if ($v['thumb_docid'] > 0) {
                        $docid[] = $v['thumb_docid'];
                    }

                    if ($v['brand_id'] > 0) {
                        $a              = $this->getBrand($v['brand_id']);
                        $b              = $this->getClasslist($a['caid']);
                        $rs[$k]['city'] = $b['name'];
                    }

                }
                if ($docid) {
                    $docs = $this->getDocs($docid);
                }

            }

            if ($rs) {
                foreach ($rs as $r) {
                    $goods_ids[] = $r['goods_id'];
                    // $shopid[]    = $r['shopid'];
                }
                $sql       = "SELECT `goods_id`,`number` FROM {$this->_prefix['primary']}goods_stock WHERE `goods_id` IN (" . implode(",", $goods_ids) . ")";
                $stockdata = $this->sql($sql);
                foreach ($stockdata as $v) {
                    $goods_number[$v['goods_id']] = $v['number'];
                }
                /*$sql      = "SELECT `shopid`,name FROM {$this->_prefix['primary']}shop_info WHERE   `shopid` IN (" . implode(",", $shopid) . ")";
                $shopdata = $this->sql($sql);
                foreach ($shopdata as $v) {
                $shopinfo[$v['shopid']] = $v['name'];
                }*/

                foreach ($rs as $k => $v) {
                    $rs[$k]['goods_number'] = $goods_number[$v['goods_id']];
                    // $rs[$k]['shop_name']    = $shopinfo[$v['shopid']];
                }
            }

        }

        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt / $pagesize),
            'count'   => $cnt,
            'data'    => $rs,
            'para'    => $para,
            'docs'    => $docs,
        );
    }

    //批量操作商品
    public function saveBatch($ids, $act)
    {
        $code    = 900;
        $ids_arr = explode(",", $ids);
        foreach ($ids_arr as $r) {
            $id = intval($r);
            if ($id > 0) {
                $goods_id[] = $id;
            }

        }
        if ($goods_id) {
            $where = " WHERE  `goods_id` IN (" . implode(",", array_unique($goods_id)) . ")";
            switch ($act) {
                case "delete":
                    $set = " `is_delete`=1";
                    break;
                case "on_sale":
                    $set = " `is_on_sale`=1";
                    break;
                case "off_sale":
                    $set = " `is_on_sale`=0";
                    break;
                case "is_best":
                    $set = " `is_best`=1";
                    break;
                case "is_hot":
                    $set = " `is_hot`=1";
                    break;
                case "is_new":
                    $set = " `is_new`=1";
                    break;
            }

            $sql = "UPDATE {$this->_prefix['primary']}goods_data SET " . $set . ",last_aid=" . $this->_auth['aid'] . ",last_edit=" . time() . $where;

            $rc = $this->sql($sql);
            if ($rc > 0) {
                $code = 200;
            } else {
                $code = 403;
            }

        }
        return $code;
    }

    //保存文档
    public function saveDocument($name, $filename, $filesize, $format, $create_time)
    {
        $sql = "INSERT INTO {$this->_prefix['primary']}documents
        (`shopid`,`name`,`filename`,`filesize`,`format`,`create_time`) VALUES
        (1,'" . $name . "','" . $filename . "'," . $filesize . ",'" . $format . "'," . $create_time . ")";

        $docid = $this->sql($sql);
        return $docid;
    }

    //删除商品
    public function deleteGoods($goods_id)
    {
        if (is_array($goods_id)) {
            $where = " `goods_id` IN (" . implode(",", array_unique($goods_id)) . ")";
        } else {
            $where = " `goods_id`=" . intval($goods_id);
        }

        $sql = "UPDATE {$this->_prefix['primary']}goods_data SET `is_delete`=1,`last_aid`=" . $this->_auth['aid'] . ",`last_edit`=" . $_SERVER['REQUEST_TIME'] . " WHERE " . $where . "";

        $rc = $this->sql($sql);
        if ($rc > 0) {
            $code = 200;
        } else {
            $code = 403;
        }

        return $code;

    }

    //保存商品
    public function saveGoods($da, $file, $goods_id = 0)
    {

        $code      = 900;
        $savegoods = true;

        $field['relevance_id'] = 0;
        $relevances            = addslashes(htmlspecialchars(trim($da['relevance_id'])));
        if (!empty($relevances)) {

            $relevance = explode('-', $relevances);
            if (is_numeric($relevance[0])) {
                $field['relevance_id'] = $relevance[0];
            }
        }

        $express_setting = array(
            'extra_money' => $da['extra_money'],
            'no_sale'     => $da['no_sale'],
        );

        $field['express_setting'] = json_encode($express_setting);

        $field['goods_title'] = addslashes(htmlspecialchars(trim($da['goods_title'])));
        $field['rele_title']  = addslashes(htmlspecialchars(trim($da['rele_title'])));
        $field['pic_docid']   = $da['pic_docid'];
        $field['show_docid']  = $da['show_docid'];
        $field['thumb_docid'] = $da['thumb_docid'];

        $field['goods_name'] = addslashes(htmlspecialchars(trim($da['goods_name'])));
        $field['goods_sn']   = addslashes(htmlspecialchars(trim($da['goods_sn'])));
        $field['caid']       = intval($da['caid']);
        $field['weight']     = intval($da['weight']);

        $field['brand_id']       = intval($da['brand_id']);
        $field['supplierid']     = intval($da['supplierid']);
        $field['purchasing_num'] = intval($da['purchasing_num']);

        // 价格
        $field['shop_price']     = number_format($da['shop_price'], 2, '.', '');
        $field['market_price']   = number_format($da['market_price'], 2, '.', '');
        $field['purchase_price'] = number_format($da['purchase_price'], 2, '.', '');
        $field['ximi_price']     = number_format($da['ximi_price'], 2, '.', '');
        $field['coupon_price']   = intval($da['coupon_price']);
        // 赠送
        $field['give_ticket'] = intval($da['give_ticket']);
        $field['give_coupon'] = intval($da['give_coupon']);
        // 分润价格
        $field['price_me']     = number_format($da['price_me'], 2, '.', '');
        $field['price_level1'] = number_format($da['price_level1'], 2, '.', '');
        $field['price_level2'] = number_format($da['price_level2'], 2, '.', '');
        //
        $field['is_best']          = intval($da['is_best']) == 1 ? 1 : 0;
        $field['is_free_shipping'] = intval($da['is_free_shipping']) == 1 ? 1 : 0;
        $field['is_hot']           = intval($da['is_hot']) == 1 ? 1 : 0;
        $field['goods_type']       = intval($da['goods_type']);
        $field['maker_level']      = intval($da['maker_level']);
        $field['can_use_gold']     = intval($da['can_use_gold']) == 1 ? 1 : 0;

        // 商品折扣计算
        $field['discount_percent'] = 1;

        if ($field['shop_price'] > 0 && $field['market_price'] > 0 && $field['market_price'] > $field['shop_price']) {

            $field['discount_percent'] = number_format($field['shop_price'] / $field['market_price'], 2, ".", "");
        }

        $field['goods_unit']     = addslashes(htmlspecialchars(trim($da['goods_unit'])));
        $field['is_on_sale']     = intval($da['is_on_sale']) == 1 ? 1 : 0;
        $field['upgrade_goods']  = intval($da['upgrade_goods']) == 1 ? 1 : 0;
        $field['can_not_reback'] = intval($da['can_not_reback']) == 1 ? 1 : 0;

        //重量
        $field['goods_weight']  = number_format($da['goods_weight'], 2, '.', '');
        $field['goods_desc']    = $da['goods_desc'];
        $field['goods_barcode'] = addslashes(htmlspecialchars(trim($da['goods_barcode'])));
        $field['goods_sku']     = addslashes(htmlspecialchars(trim($da['goods_sku'])));

        //今日特卖封面图
        if ($file['pic0_big']['tmp_name'] != "" && $file['pic0_big']['size'] > 0) {

            $savegoods = false;
            if (in_array($file['pic0_big']['type'], $this->c['upload']['mimejpg'])) {

                if ($file['pic0_big']['size'] <= $this->c['upload']['size']) {
                    $format = $this->upload->rf($file['pic0_big']['name']);

                    if (in_array($format, $this->c['upload']['fm'])) {

                        //创建目录
                        $dir['date'] = $this->c['upload']['dir'] . date("Ymd", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['date'])) {
                            mkdir($dir['date']);
                        }

                        $dir['hour'] = $dir['date'] . DIRECTORY_SEPARATOR . date("H", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['hour'])) {
                            mkdir($dir['hour']);
                        }

                        $dir['minute'] = $dir['hour'] . DIRECTORY_SEPARATOR . date("i", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['minute'])) {
                            mkdir($dir['minute']);
                        }

                        if (file_exists($dir['minute'])) {

                            //移动文件
                            $filename = md5($file['pic0_big']['tmp_name'] . $_SERVER['REQUEST_TIME']) . "." . $format;
                            $filepath = $dir['minute'] . DIRECTORY_SEPARATOR . $filename;

                            if (move_uploaded_file($file['pic0_big']['tmp_name'], $filepath)) {

                                // 压缩图片
                                $this->upload->mt($filepath, $filepath, 800, 400, 90);
                                $tmpfilesize = filesize($filepath);
                                $docid       = $this->saveDocument($file['pic0_big']['name'], $filename, $tmpfilesize, $format, $_SERVER['REQUEST_TIME']);

                                if ($docid > 0) {
                                    $field['hot_docid'] = $docid;
                                    $savegoods          = true;
                                } else {
                                    $code = 701;
                                    @unlink($filepath);
                                }
                            } else {
                                $code = 705;
                            }

                        } else {
                            $code = 706;
                        }

                    } else {
                        $code = 703;
                    }

                } else {
                    $code = 704;
                }

            } else {
                $code = 703;
            }

            @unlink($file['pic0_big']['tmp_name']);
        }

        //商品大图1处理
        if ($file['pic_big']['tmp_name'] != "" && $file['pic_big']['size'] > 0) {

            $savegoods = false;
            if (in_array($file['pic_big']['type'], $this->c['upload']['mimejpg'])) {

                if ($file['pic_big']['size'] <= $this->c['upload']['size']) {
                    $format = $this->upload->rf($file['pic_big']['name']);

                    if (in_array($format, $this->c['upload']['fm'])) {

                        //创建目录
                        $dir['date'] = $this->c['upload']['dir'] . date("Ymd", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['date'])) {
                            mkdir($dir['date']);
                        }

                        $dir['hour'] = $dir['date'] . DIRECTORY_SEPARATOR . date("H", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['hour'])) {
                            mkdir($dir['hour']);
                        }

                        $dir['minute'] = $dir['hour'] . DIRECTORY_SEPARATOR . date("i", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['minute'])) {
                            mkdir($dir['minute']);
                        }

                        if (file_exists($dir['minute'])) {

                            //移动文件
                            $filename = md5($file['pic_big']['tmp_name'] . $_SERVER['REQUEST_TIME']) . "." . $format;
                            $filepath = $dir['minute'] . DIRECTORY_SEPARATOR . $filename;

                            if (move_uploaded_file($file['pic_big']['tmp_name'], $filepath)) {

                                // 压缩图片
                                $this->upload->mt($filepath, $filepath, 2000, 5000, 90);
                                $tmpfilesize = filesize($filepath);
                                $docid       = $this->saveDocument($file['pic_big']['name'], $filename, $tmpfilesize, $format, $_SERVER['REQUEST_TIME']);

                                if ($docid > 0) {
                                    $field['pic_docid']  = $docid;
                                    $pic_big['filepath'] = $filepath;
                                    $pic_big['name']     = $file['pic_big']['name'];
                                    $pic_big['format']   = $format;

                                    $savegoods = true;
                                } else {
                                    $code = 701;
                                    @unlink($filepath);
                                }
                            } else {
                                $code = 705;
                            }

                        } else {
                            $code = 706;
                        }

                    } else {
                        $code = 703;
                    }

                } else {
                    $code = 704;
                }

            } else {
                $code = 703;
            }

            @unlink($file['pic_big']['tmp_name']);
        }

        //商品大图2处理
        if ($file['pic2_big']['tmp_name'] != "" && $file['pic2_big']['size'] > 0) {

            $savegoods = false;
            if (in_array($file['pic2_big']['type'], $this->c['upload']['mimejpg'])) {

                if ($file['pic2_big']['size'] <= $this->c['upload']['size']) {
                    $format = $this->upload->rf($file['pic2_big']['name']);

                    if (in_array($format, $this->c['upload']['fm'])) {

                        //创建目录
                        $dir['date'] = $this->c['upload']['dir'] . date("Ymd", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['date'])) {
                            mkdir($dir['date']);
                        }

                        $dir['hour'] = $dir['date'] . DIRECTORY_SEPARATOR . date("H", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['hour'])) {
                            mkdir($dir['hour']);
                        }

                        $dir['minute'] = $dir['hour'] . DIRECTORY_SEPARATOR . date("i", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['minute'])) {
                            mkdir($dir['minute']);
                        }

                        if (file_exists($dir['minute'])) {

                            //移动文件
                            $filename = md5($file['pic2_big']['tmp_name'] . $_SERVER['REQUEST_TIME']) . "." . $format;
                            $filepath = $dir['minute'] . DIRECTORY_SEPARATOR . $filename;

                            if (move_uploaded_file($file['pic2_big']['tmp_name'], $filepath)) {

                                // 压缩图片
                                $this->upload->mt($filepath, $filepath, 2000, 5000, 90);
                                $tmpfilesize = filesize($filepath);
                                $docid       = $this->saveDocument($file['pic2_big']['name'], $filename, $tmpfilesize, $format, $_SERVER['REQUEST_TIME']);

                                if ($docid > 0) {
                                    $field['pic2_docid'] = $docid;

                                    $savegoods = true;
                                } else {
                                    $code = 701;
                                    @unlink($filepath);
                                }
                            } else {
                                $code = 705;
                            }

                        } else {
                            $code = 706;
                        }

                    } else {
                        $code = 703;
                    }

                } else {
                    $code = 704;
                }

            } else {
                $code = 703;
            }

            @unlink($file['pic2_big']['tmp_name']);
        }

        //商品大图3处理
        if ($file['pic3_big']['tmp_name'] != "" && $file['pic3_big']['size'] > 0) {

            $savegoods = false;
            if (in_array($file['pic3_big']['type'], $this->c['upload']['mimejpg'])) {

                if ($file['pic3_big']['size'] <= $this->c['upload']['size']) {
                    $format = $this->upload->rf($file['pic3_big']['name']);

                    if (in_array($format, $this->c['upload']['fm'])) {

                        //创建目录
                        $dir['date'] = $this->c['upload']['dir'] . date("Ymd", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['date'])) {
                            mkdir($dir['date']);
                        }

                        $dir['hour'] = $dir['date'] . DIRECTORY_SEPARATOR . date("H", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['hour'])) {
                            mkdir($dir['hour']);
                        }

                        $dir['minute'] = $dir['hour'] . DIRECTORY_SEPARATOR . date("i", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['minute'])) {
                            mkdir($dir['minute']);
                        }

                        if (file_exists($dir['minute'])) {

                            //移动文件
                            $filename = md5($file['pic3_big']['tmp_name'] . $_SERVER['REQUEST_TIME']) . "." . $format;
                            $filepath = $dir['minute'] . DIRECTORY_SEPARATOR . $filename;

                            if (move_uploaded_file($file['pic3_big']['tmp_name'], $filepath)) {

                                // 压缩图片
                                $this->upload->mt($filepath, $filepath, 2000, 5000, 90);
                                $tmpfilesize = filesize($filepath);
                                $docid       = $this->saveDocument($file['pic3_big']['name'], $filename, $tmpfilesize, $format, $_SERVER['REQUEST_TIME']);

                                if ($docid > 0) {
                                    $field['pic3_docid'] = $docid;

                                    $savegoods = true;
                                } else {
                                    $code = 701;
                                    @unlink($filepath);
                                }
                            } else {
                                $code = 705;
                            }

                        } else {
                            $code = 706;
                        }

                    } else {
                        $code = 703;
                    }

                } else {
                    $code = 704;
                }

            } else {
                $code = 703;
            }

            @unlink($file['pic3_big']['tmp_name']);
        }

        //商品大图4处理
        if ($file['pic4_big']['tmp_name'] != "" && $file['pic4_big']['size'] > 0) {

            $savegoods = false;
            if (in_array($file['pic4_big']['type'], $this->c['upload']['mimejpg'])) {

                if ($file['pic4_big']['size'] <= $this->c['upload']['size']) {
                    $format = $this->upload->rf($file['pic4_big']['name']);

                    if (in_array($format, $this->c['upload']['fm'])) {

                        //创建目录
                        $dir['date'] = $this->c['upload']['dir'] . date("Ymd", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['date'])) {
                            mkdir($dir['date']);
                        }

                        $dir['hour'] = $dir['date'] . DIRECTORY_SEPARATOR . date("H", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['hour'])) {
                            mkdir($dir['hour']);
                        }

                        $dir['minute'] = $dir['hour'] . DIRECTORY_SEPARATOR . date("i", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['minute'])) {
                            mkdir($dir['minute']);
                        }

                        if (file_exists($dir['minute'])) {

                            //移动文件
                            $filename = md5($file['pic4_big']['tmp_name'] . $_SERVER['REQUEST_TIME']) . "." . $format;
                            $filepath = $dir['minute'] . DIRECTORY_SEPARATOR . $filename;

                            if (move_uploaded_file($file['pic4_big']['tmp_name'], $filepath)) {

                                // 压缩图片
                                $this->upload->mt($filepath, $filepath, 2000, 5000, 90);
                                $tmpfilesize = filesize($filepath);
                                $docid       = $this->saveDocument($file['pic4_big']['name'], $filename, $tmpfilesize, $format, $_SERVER['REQUEST_TIME']);

                                if ($docid > 0) {
                                    $field['pic4_docid'] = $docid;

                                    $savegoods = true;
                                } else {
                                    $code = 701;
                                    @unlink($filepath);
                                }
                            } else {
                                $code = 705;
                            }

                        } else {
                            $code = 706;
                        }

                    } else {
                        $code = 703;
                    }

                } else {
                    $code = 704;
                }

            } else {
                $code = 703;
            }

            @unlink($file['pic4_big']['tmp_name']);
        }

        //商品大图5处理
        if ($file['pic5_big']['tmp_name'] != "" && $file['pic5_big']['size'] > 0) {

            $savegoods = false;
            if (in_array($file['pic5_big']['type'], $this->c['upload']['mimejpg'])) {

                if ($file['pic5_big']['size'] <= $this->c['upload']['size']) {
                    $format = $this->upload->rf($file['pic5_big']['name']);

                    if (in_array($format, $this->c['upload']['fm'])) {

                        //创建目录
                        $dir['date'] = $this->c['upload']['dir'] . date("Ymd", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['date'])) {
                            mkdir($dir['date']);
                        }

                        $dir['hour'] = $dir['date'] . DIRECTORY_SEPARATOR . date("H", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['hour'])) {
                            mkdir($dir['hour']);
                        }

                        $dir['minute'] = $dir['hour'] . DIRECTORY_SEPARATOR . date("i", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['minute'])) {
                            mkdir($dir['minute']);
                        }

                        if (file_exists($dir['minute'])) {

                            //移动文件
                            $filename = md5($file['pic5_big']['tmp_name'] . $_SERVER['REQUEST_TIME']) . "." . $format;
                            $filepath = $dir['minute'] . DIRECTORY_SEPARATOR . $filename;

                            if (move_uploaded_file($file['pic5_big']['tmp_name'], $filepath)) {

                                // 压缩图片
                                $this->upload->mt($filepath, $filepath, 2000, 5000, 90);
                                $tmpfilesize = filesize($filepath);
                                $docid       = $this->saveDocument($file['pic5_big']['name'], $filename, $tmpfilesize, $format, $_SERVER['REQUEST_TIME']);

                                if ($docid > 0) {
                                    $field['pic5_docid'] = $docid;

                                    $savegoods = true;
                                } else {
                                    $code = 701;
                                    @unlink($filepath);
                                }
                            } else {
                                $code = 705;
                            }

                        } else {
                            $code = 706;
                        }

                    } else {
                        $code = 703;
                    }

                } else {
                    $code = 704;
                }

            } else {
                $code = 703;
            }

            @unlink($file['pic5_big']['tmp_name']);
        }

        //如果选择了自动生成缩略图，并且已经上传了大图
        if ($da['auto_thumb'] == 1 && $pic_big['filepath'] != "") {
            $savegoods = false;
            $filename  = md5($pic_big['filepath'] . $_SERVER['REQUEST_TIME']) . "." . $pic_big['format'];
            $filepath  = $dir['minute'] . DIRECTORY_SEPARATOR . $filename;
            $this->upload->mt($pic_big['filepath'], $filepath, 600, 600);

            if (file_exists($filepath)) {
                $filesize = filesize($filepath);
                $docid    = $this->saveDocument($pic_big['name'], $filename, $filesize, $pic_big['format'], $_SERVER['REQUEST_TIME']);
                if ($docid > 0) {
                    $field['thumb_docid'] = $docid;
                    $savegoods            = true;
                } else {
                    $code = 701;
                    @unlink($filepath);
                }
            } else {
                $code = 707;
            }

        }
        //如果选择了缩略图文件
        elseif ($file['pic_thumb']['tmp_name'] != "" && $file['pic_thumb']['size'] > 0) {
            $savegoods = false;
            if (in_array($file['pic_thumb']['type'], $this->c['upload']['mime'])) {

                if ($file['pic_thumb']['size'] <= $this->c['upload']['size']) {
                    $format = $this->upload->rf($file['pic_thumb']['name']);

                    if (in_array($format, $this->c['upload']['fm'])) {

                        //创建目录
                        $dir['date'] = $this->c['upload']['dir'] . date("Ymd", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['date'])) {
                            mkdir($dir['date']);
                        }

                        $dir['hour'] = $dir['date'] . DIRECTORY_SEPARATOR . date("H", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['hour'])) {
                            mkdir($dir['hour']);
                        }

                        $dir['minute'] = $dir['hour'] . DIRECTORY_SEPARATOR . date("i", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['minute'])) {
                            mkdir($dir['minute']);
                        }

                        if (file_exists($dir['minute'])) {

                            //移动文件
                            $filename = md5($file['pic_thumb']['tmp_name'] . $_SERVER['REQUEST_TIME']) . "." . $format;
                            $filepath = $dir['minute'] . DIRECTORY_SEPARATOR . $filename;

                            if (move_uploaded_file($file['pic_thumb']['tmp_name'], $filepath)) {
                                $this->upload->mt($filepath, $filepath, 600, 600);
                                $docid = $this->saveDocument($file['pic_thumb']['name'], $filename, @filesize($filepath), $format, $_SERVER['REQUEST_TIME']);

                                if ($docid > 0) {
                                    $field['thumb_docid'] = $docid;
                                    $savegoods            = true;
                                } else {
                                    $code = 701;
                                    @unlink($filepath);
                                }
                            } else {
                                $code = 705;
                            }

                        } else {
                            $code = 706;
                        }

                    } else {
                        $code = 703;
                    }

                } else {
                    $code = 704;
                }

            } else {
                $code = 703;
            }

        }   

        // print_r($field);

        //保存商品
        if ($field['goods_name'] != "" && $savegoods) {

            $code = 403;
            //开始事务
            $this->db->begin();
            $rollback = true;
            $config   = $this->getSetting();
            //修改
            if ($goods_id > 0) {

                $goods = $this->getSingleGoods($goods_id);
                if ($goods) {
                    $res = array(0 => '', 1 => '', 2 => '', 3 => '');
                    //其他必须字段
                    $field['last_edit'] = $field['last_update'] = $_SERVER['REQUEST_TIME'];
                    $field['last_aid']  = $this->_auth['aid'];

                    //修改商品
                    $sql = "UPDATE {$this->_prefix['primary']}goods_data SET ";

                    foreach ($field as $key => $value) {
                        $upsql[] = "`" . $key . "`='" . $value . "'";
                    }
                    $sql .= implode(",", $upsql) . " WHERE `goods_id`=" . $goods['goods_id'];
                    $rcnum = $this->sql($sql);
                    if ($rcnum) {
                        if ($field['relevance_id']) {
                            $sql  = "SELECT * FROM {$this->_prefix['primary']}goods_relevance WHERE `id`=" . $field['relevance_id'];
                            $rele = $this->db->getrow($sql);
                            if ($rele) {
                                $goods_ids = trim($rele['goods_ids'] . ',' . $goods_id, ',');
                                $sql       = "UPDATE {$this->_prefix['primary']}goods_relevance SET goods_ids='" . $goods_ids . "',`update_time`=" . $_SERVER['REQUEST_TIME'] . " where id=" . $field['relevance_id'];
                                $rele_id   = $this->sql($sql);
                                if ($rele_id) {
                                    $code = 200;
                                    $this->db->commit();
                                    $rollback = false;

                                }
                            }
                        } else {
                            $code = 200;
                            $this->db->commit();
                            $rollback = false;

                        }

                    }
                } else {
                    $code = 404;
                }

            }
            //新增
            else {
                //其他必须字段
                $field['add_time'] = $field['last_edit'] = $field['last_update'] = $_SERVER['REQUEST_TIME'];
                $field['last_aid'] = $field['create_aid'] = $this->_auth['aid'];

                foreach ($field as $key => $value) {
                    $keys[]   = "`" . $key . "`";
                    $values[] = "'" . $value . "'";

                }

                //插入商品
                $sql = "INSERT INTO {$this->_prefix['primary']}goods_data (" . implode(",", $keys) . ") VALUES (" . implode(",", $values) . ")";

                $goods_id = $this->sql($sql);
                if ($goods_id > 0) {

                    $done = true;

                    // 插入默认库存信息
                    $sql       = "INSERT INTO {$this->_prefix['primary']}goods_stock (`goods_id`,`number`,`last_aid`,`last_edit`) VALUES (" . $goods_id . ",0," . $this->_auth['aid'] . "," . $field['add_time'] . ")";
                    $savestock = $this->sql($sql);
                    if (!$savestock || $savestock == 0) {
                        $done = false;
                    }

                    if ($done) {
                        if ($field['relevance_id']) {
                            $sql  = "SELECT * FROM {$this->_prefix['primary']}goods_relevance WHERE `id`=" . $field['relevance_id'];
                            $rele = $this->db->getrow($sql);
                            if ($rele) {
                                $goods_ids = trim($rele['goods_ids'] . ',' . $goods_id, ',');
                                $sql       = "UPDATE {$this->_prefix['primary']}goods_relevance SET goods_ids='" . $goods_ids . "',`update_time`=" . $_SERVER['REQUEST_TIME'] . " where id=" . $field['relevance_id'];
                                $rele_id   = $this->sql($sql);
                                if ($rele_id) {
                                    $code = 200;
                                    $this->db->commit();
                                    $rollback = false;

                                }
                            }
                        } else {
                            $code = 200;
                            $this->db->commit();
                            $rollback = false;

                        }

                    }

                }

            } //end of add

            if ($rollback) {
                $this->db->rollback();
            }

        }

        return $code;
    }

    // 保存商品分润
    public function saveGoodsCommission($da)
    {
        $code = 900;

        $goods_id = intval($da['goods_id']);
        if ($goods_id > 0) {
            unset($da['act']);
            unset($da['ref']);
            unset($da['goods_id']);

            $commission_setting = json_encode($da);

            $sql = "UPDATE {$this->_prefix['primary']}goods_data SET `commission_setting`='" . $commission_setting . "',`last_aid`=" . $this->_auth['aid'] . ",`last_edit`=" . $_SERVER['REQUEST_TIME'] . " WHERE `goods_id`=" . $goods_id;
            $rc  = $this->sql($sql);

            if ($rc > 0) {
                $code = 200;
            } else {
                $code = 403;
            }
        }

        return $code;
    }

    // 获取指定下属类别
    public function getSmlCate($fucaid = 0)
    {
        $sql  = "SELECT `caid` FROM {$this->_prefix['primary']}goods_category WHERE `fucaid`=" . intval($fucaid) . " AND `stat`<3";
        $data = $this->sql($sql);
        if ($data) {
            foreach ($data as $r) {
                $new[] = $r['caid'];
            }
            return $new;
        }
        return false;
    }

    //获取所有类别
    public function getCategory($caid = 0, $isfucaid = false, $shopid = 0)
    {
        if ($isfucaid) {
            $tsql = " AND `fucaid`=" . intval($caid);
        } elseif ($caid > 0) {
            $tsql = " AND `caid`=" . intval($caid);
        }

        if ($shopid > 0) {
            $tsql = " AND `shopid`=" . intval($shopid);
        }

        $sql = "SELECT * FROM {$this->_prefix['primary']}goods_category WHERE  `stat`=1  " . $tsql . " ORDER BY `fucaid` ASC,`sort` ASC,`stat` ASC,`caid` ASC ";

        if ($caid > 0 && !$isfucaid) {
            $newdata = $this->db->getrow($sql);
        } else {
            $data = $this->sql($sql);
            if ($data) {
                if ($isfucaid) {
                    $newdata = $data;
                } else {
                    foreach ($data as $r) {
                        $newdata[$r['fucaid']][$r['caid']] = $r;
                    }
                }
            }
        }
        return $newdata;
    }

    //获取所有类别
    public function getCategoryAll($caid = 0)
    {

        $tsql = " AND `fucaid`=" . intval($caid);
        $sql  = "SELECT * FROM {$this->_prefix['primary']}goods_category WHERE  `stat`=1  " . $tsql . " ORDER BY `fucaid` ASC,`sort` ASC,`stat` ASC,`caid` ASC ";
        $data = $this->sql($sql);

        return $data;
    }

    public function getCatePid($caid = 0)
    {

        $tsql   = " AND `caid`=" . intval($caid);
        $sql    = "SELECT `fucaid` FROM {$this->_prefix['primary']}goods_category WHERE  `stat`=1  " . $tsql;
        $fucaid = $this->db->getone($sql);
        $arr    = [];
        if ($fucaid) {

            $sql           = "SELECT * FROM {$this->_prefix['primary']}goods_category WHERE  `stat`=1 AND `fucaid`=" . $fucaid . " ORDER BY `fucaid` ASC,`sort` ASC,`stat` ASC,`caid` ASC ";
            $data          = $this->sql($sql);
            $arr['fucaid'] = $fucaid;
            $arr['data']   = $data;
        }

        return $arr;
    }

    //保存分类排序
    public function saveCategorySort($da)
    {
        $code = 900;
        if ($da['value'] != "") {
            $ids = json_decode($da['value'], true);
            foreach ($ids as $k => $r) {
                $sql = "UPDATE {$this->_prefix['primary']}goods_category SET `sort`=" . $k . " WHERE `caid`=" . intval($r['id']);
                $this->sql($sql);
            }
            $code = 200;
        }
        return $code;
    }

    //保存分类排序
    public function saveCategorySorts($da)
    {
        $code = 900;
        if ($da['value'] != "") {
            $ids = json_decode($da['value'], true);
            foreach ($ids as $k => $r) {
                $sql = "UPDATE {$this->_prefix['primary']}brand_category SET `sort`=" . $k . " WHERE `caid`=" . intval($r['id']);
                $this->sql($sql);
            }
            $code = 200;
        }
        return $code;
    }

    //保存分类
    public function saveCategory($da, $file, $caid = 0)
    {

        $code   = 900;
        $name   = addslashes(htmlspecialchars(trim($da['name'])));
        $names  = addslashes(htmlspecialchars(trim($da['names'])));
        $stat   = intval($da['stat']);
        $fucaid = intval($da['fucaid']);

        //分类logo处理
        if ($file['pic_big']['tmp_name'] != "" && $file['pic_big']['size'] > 0) {
            $savegoods = false;
            if (in_array($file['pic_big']['type'], $this->c['upload']['mime'])) {

                if ($file['pic_big']['size'] <= $this->c['upload']['size']) {
                    $format = $this->upload->rf($file['pic_big']['name']);

                    if (in_array($format, $this->c['upload']['fm'])) {

                        //创建目录
                        $dir['date'] = $this->c['upload']['dir'] . date("Ymd", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['date'])) {
                            mkdir($dir['date']);
                        }

                        $dir['hour'] = $dir['date'] . DIRECTORY_SEPARATOR . date("H", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['hour'])) {
                            mkdir($dir['hour']);
                        }

                        $dir['minute'] = $dir['hour'] . DIRECTORY_SEPARATOR . date("i", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['minute'])) {
                            mkdir($dir['minute']);
                        }

                        if (file_exists($dir['minute'])) {

                            //移动文件
                            $filename = md5($file['pic_big']['tmp_name'] . $_SERVER['REQUEST_TIME']) . "." . $format;
                            $filepath = $dir['minute'] . DIRECTORY_SEPARATOR . $filename;

                            if (move_uploaded_file($file['pic_big']['tmp_name'], $filepath)) {
                                $docid = $this->saveDocument($file['pic_big']['name'], $filename, $file['pic_big']['size'], $format, $_SERVER['REQUEST_TIME']);
                                if ($docid > 0) {
                                    $field['pic_docid']  = $docid;
                                    $pic_big['filepath'] = $filepath;
                                    $pic_big['name']     = $file['pic_big']['name'];
                                    $pic_big['format']   = $format;
                                    $savegoods           = true;
                                } else {
                                    $code = 701;
                                    @unlink($filepath);
                                }
                            } else {
                                $code = 705;
                            }

                        } else {
                            $code = 706;
                        }

                    } else {
                        $code = 703;
                    }

                } else {
                    $code = 704;
                }

            } else {
                $code = 703;
            }

        }

        //分类广告处理
        if ($file['pic_img']['tmp_name'] != "" && $file['pic_img']['size'] > 0) {
            $savegoods = false;
            if (in_array($file['pic_img']['type'], $this->c['upload']['mime'])) {

                if ($file['pic_img']['size'] <= $this->c['upload']['size']) {
                    $format = $this->upload->rf($file['pic_img']['name']);

                    if (in_array($format, $this->c['upload']['fm'])) {

                        //创建目录
                        $dir['date'] = $this->c['upload']['dir'] . date("Ymd", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['date'])) {
                            mkdir($dir['date']);
                        }

                        $dir['hour'] = $dir['date'] . DIRECTORY_SEPARATOR . date("H", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['hour'])) {
                            mkdir($dir['hour']);
                        }

                        $dir['minute'] = $dir['hour'] . DIRECTORY_SEPARATOR . date("i", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['minute'])) {
                            mkdir($dir['minute']);
                        }

                        if (file_exists($dir['minute'])) {

                            //移动文件
                            $filename = md5($file['pic_img']['tmp_name'] . $_SERVER['REQUEST_TIME']) . "." . $format;
                            $filepath = $dir['minute'] . DIRECTORY_SEPARATOR . $filename;

                            if (move_uploaded_file($file['pic_img']['tmp_name'], $filepath)) {
                                $docids = $this->saveDocument($file['pic_img']['name'], $filename, $file['pic_img']['size'], $format, $_SERVER['REQUEST_TIME']);
                                if ($docids > 0) {
                                    $field['pic_docid']  = $docids;
                                    $pic_img['filepath'] = $filepath;
                                    $pic_img['name']     = $file['pic_img']['name'];
                                    $pic_img['format']   = $format;
                                    $savegoods           = true;
                                } else {
                                    $code = 701;
                                    @unlink($filepath);
                                }
                            } else {
                                $code = 705;
                            }

                        } else {
                            $code = 706;
                        }

                    } else {
                        $code = 703;
                    }

                } else {
                    $code = 704;
                }

            } else {
                $code = 703;
            }

        }

        //修改
        if ($caid > 0) {

            $sql = "SELECT * FROM {$this->_prefix['primary']}goods_category WHERE `caid`=" . intval($caid) . "  AND `stat`<3";
            $rs  = $this->db->getrow($sql);

            if ($rs) {
                if ($docid) {
                    $s = ',`docid`=' . $docid . '';
                } else {
                    $s = '';
                }
                if ($docids) {
                    $t = ',`addocid`=' . $docids . '';
                } else {
                    $t = '';
                }
                $sql = "UPDATE {$this->_prefix['primary']}goods_category SET `stat`=" . $stat . ",`fucaid`=" . $fucaid . ",`name`='" . $name . "',`names`='" . $names . "',`last_staffid`=3,`last_staffedit`=" . $_SERVER['REQUEST_TIME'] . $s . $t . " WHERE `caid`=" . $rs['caid'];
                $rd  = $this->sql($sql);
                if ($rd > 0) {
                    $code = 200;
                } else {
                    $code = 403;
                }

            } else {
                $code = 404;
            }

        }
        //新增
        else {
            if ($da['name'] != "") {
                if (intval($docid) <= 0) {
                    $docid = 0;
                }
                if (intval($docids) <= 0) {
                    $docids = 0;
                }
                $sql = "INSERT INTO {$this->_prefix['primary']}goods_category
                    (`shopid`,`name`,`names`,`fucaid`,`stat`,`last_staffid`,`last_staffedit`,`docid`,`addocid`) VALUES
                    (1,'" . $name . "','" . $names . "'," . $fucaid . "," . $stat . ",3," . $_SERVER['REQUEST_TIME'] . "," . $docid . "," . $docids . ")";
                $rd = $this->sql($sql);

                if ($rd > 0) {
                    $code = 200;
                } else {
                    $code = 403;
                }

            }
        }
        return $code;

    }

    //获取品牌
    public function getBrandShow($para)
    {
        if ($para['keyword']) {
            $where .= " AND `name` LIKE '%" . $para['keyword'] . "%' OR `names` LIKE '%" . $para['keyword'] . "%' ";
        }
        if ($para['stat'] > 0) {
            $where .= " AND `stat`=" . $para['stat'];
        }
        if ($para['caid'] > 0) {
            $where .= " AND `caid`=" . $para['caid'];
        }

        $sql  = "SELECT * FROM {$this->_prefix['primary']}brand WHERE  `stat`<3 " . $where . " ORDER BY `name` ASC";
        $data = $this->sql($sql);

        return array(
            'data' => $data,
            'para' => $para,
        );
    }

    //获取货源品牌
    public function getBrand($brand_id = 0, $shopid = 0, $type = 0)
    {
        if ($type > 0) {
            $tsql = "`stat`=1";
        } else {

            $tsql = "`stat`!=3";
        }
        if ($brand_id > 0) {
            $tsql .= " AND `brand_id`=" . intval($brand_id);
        }

        if ($shopid > 0) {
            $tsql .= " AND `shopid`=" . intval($shopid);
        }

        $sql = "SELECT * FROM {$this->_prefix['primary']}brand WHERE  " . $tsql . " ORDER BY `name` ASC";
        if ($brand_id > 0) {
            $newdata = $this->db->getrow($sql);
        } else {
            $data = $this->sql($sql);
            if ($data) {
                foreach ($data as $r) {
                    $newdata[$r['brand_id']] = $r;
                }
            }
        }

        return $newdata;
    }

    //保存品牌
    public function saveBrand($da, $file, $brand_id = 0)
    {

        $code         = 900;
        $name         = addslashes(htmlspecialchars(trim($da['name']))); //品牌中文名称
        $names        = addslashes(htmlspecialchars(trim($da['names']))); //品牌英文名称
        $weight       = intval($da['weight']); //品牌权重
        $company_name = addslashes(htmlspecialchars(trim($da['company_name']))); //公司名称
        $instruction  = addslashes(htmlspecialchars(trim($da['instruction']))); //详细说明
        $caid         = intval($da['caid']);
        $stat         = intval($da['stat']);

        //封面大图
        if ($file['cover_pic']['tmp_name'] != "" && $file['cover_pic']['size'] > 0) {
            $savegoods = false;
            if (in_array($file['cover_pic']['type'], $this->c['upload']['mime'])) {

                if ($file['cover_pic']['size'] <= $this->c['upload']['size']) {
                    $format = $this->upload->rf($file['cover_pic']['name']);

                    if (in_array($format, $this->c['upload']['fm'])) {

                        //创建目录
                        $dir['date'] = $this->c['upload']['dir'] . date("Ymd", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['date'])) {
                            mkdir($dir['date']);
                        }

                        $dir['hour'] = $dir['date'] . DIRECTORY_SEPARATOR . date("H", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['hour'])) {
                            mkdir($dir['hour']);
                        }

                        $dir['minute'] = $dir['hour'] . DIRECTORY_SEPARATOR . date("i", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['minute'])) {
                            mkdir($dir['minute']);
                        }

                        if (file_exists($dir['minute'])) {

                            //移动文件
                            $filename = md5($file['cover_pic']['tmp_name'] . $_SERVER['REQUEST_TIME']) . "." . $format;
                            $filepath = $dir['minute'] . DIRECTORY_SEPARATOR . $filename;

                            if (move_uploaded_file($file['cover_pic']['tmp_name'], $filepath)) {

                                $docid = $this->saveDocument($file['cover_pic']['name'], $filename, $file['cover_pic']['size'], $format, $_SERVER['REQUEST_TIME']);

                                if ($docid > 0) {
                                    $field['pic_docid']  = $docid;
                                    $pic_big['filepath'] = $filepath;
                                    $pic_big['name']     = $file['cover_pic']['name'];
                                    $pic_big['format']   = $format;

                                    $savegoods = true;
                                } else {
                                    $code = 701;
                                    @unlink($filepath);
                                }
                            } else {
                                $code = 705;
                            }

                        } else {
                            $code = 706;
                        }

                    } else {
                        $code = 703;
                    }

                } else {
                    $code = 704;
                }

            } else {
                $code = 703;
            }

        }

        //品牌logo
        if ($file['brand_pic']['tmp_name'] != "" && $file['brand_pic']['size'] > 0) {
            $savegoods = false;
            if (in_array($file['brand_pic']['type'], $this->c['upload']['mime'])) {

                if ($file['brand_pic']['size'] <= $this->c['upload']['size']) {
                    $format = $this->upload->rf($file['brand_pic']['name']);

                    if (in_array($format, $this->c['upload']['fm'])) {

                        //创建目录
                        $dir['date'] = $this->c['upload']['dir'] . date("Ymd", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['date'])) {
                            mkdir($dir['date']);
                        }

                        $dir['hour'] = $dir['date'] . DIRECTORY_SEPARATOR . date("H", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['hour'])) {
                            mkdir($dir['hour']);
                        }

                        $dir['minute'] = $dir['hour'] . DIRECTORY_SEPARATOR . date("i", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['minute'])) {
                            mkdir($dir['minute']);
                        }

                        if (file_exists($dir['minute'])) {

                            //移动文件
                            $filename = md5($file['brand_pic']['tmp_name'] . $_SERVER['REQUEST_TIME']) . "." . $format;
                            $filepath = $dir['minute'] . DIRECTORY_SEPARATOR . $filename;

                            if (move_uploaded_file($file['brand_pic']['tmp_name'], $filepath)) {

                                $docids = $this->saveDocument($file['brand_pic']['name'], $filename, $file['brand_pic']['size'], $format, $_SERVER['REQUEST_TIME']);

                                if ($docids > 0) {
                                    $field['pic_docid']  = $docids;
                                    $pic_big['filepath'] = $filepath;
                                    $pic_big['name']     = $file['brand_pic']['name'];
                                    $pic_big['format']   = $format;

                                    $savegoods = true;
                                } else {
                                    $code = 701;
                                    @unlink($filepath);
                                }
                            } else {
                                $code = 705;
                            }

                        } else {
                            $code = 706;
                        }

                    } else {
                        $code = 703;
                    }

                } else {
                    $code = 704;
                }

            } else {
                $code = 703;
            }

        }

        //修改
        if ($brand_id > 0) {

            $sql = "SELECT * FROM {$this->_prefix['primary']}brand WHERE `brand_id`=" . intval($brand_id) . " AND `stat`<3";
            $rs  = $this->db->getrow($sql);
            if ($rs) {
                if ($docid) {
                    $s = ',`cover_pic`=' . $docid . '';
                } else {
                    $s = '';
                }
                if ($docids) {
                    $sn = ',`brand_pic`=' . $docids . '';
                } else {
                    $sn = '';
                }
                $sql = "UPDATE {$this->_prefix['primary']}brand SET `stat`=" . $stat . ",`name`='" . $name . "',`names`='" . $names . "',`weight`='" . $weight . "',`company_name`='" . $company_name . "',`caid`='" . $caid . "',`instruction`='" . $instruction . "',`last_staffid`=3,`last_staffedit`=" . $_SERVER['REQUEST_TIME'] . "" . $s . $sn . " WHERE `brand_id`=" . $rs['brand_id'];
                $rd  = $this->sql($sql);
                if ($rd > 0) {
                    if ($weight) {
                        $sql = " UPDATE {$this->_prefix['primary']}goods_data SET `weight`=`weight` - " . $rs['weight'] . " + " . $weight . " WHERE `brand_id`=" . $brand_id;
                        $wd  = $this->sql($sql);
                    }
                    $code = 200;
                } else {
                    $code = 403;
                }

            } else {
                $code = 404;
            }

        }
        //新增
        else {
            if ($da['name'] != "") {
                if (intval($docid <= 0)) {
                    $docid = 0;
                }

                if (intval($docids <= 0)) {
                    $docids = 0;
                }

                // 查找是否重名
                $sql = "SELECT `brand_id` FROM {$this->_prefix['primary']}brand WHERE  `name`='" . $name . "' AND `stat`<3";
                $rs  = $this->db->getone($sql);
                if (!$rs) {
                    $sql = "INSERT INTO {$this->_prefix['primary']}brand
                        (`caid`,`shopid`,`name`,`names`,`weight`,`cover_pic`,`brand_pic`,`company_name`,`instruction`,`stat`,`last_staffid`,`last_staffedit`) VALUES
                        ('" . $caid . "',1,'" . $name . "','" . $names . "','" . $weight . "','" . $docid . "','" . $docids . "','" . $company_name . "','" . $instruction . "'," . $stat . ",3," . $_SERVER['REQUEST_TIME'] . ")";

                    $rd = $this->sql($sql);

                    if ($rd > 0) {
                        $code = 200;
                    } else {
                        $code = 403;
                    }

                } else {
                    $code = 600;
                }

            }
        }
        return $code;

    }

    public function getNewDocs($docid)
    {
        $where = " WHERE `docid`=" . intval($docid);
        $sql   = "SELECT `docid`,`filename`,`create_time` FROM {$this->_prefix['primary']}documents " . $where;
        $rs    = $this->db->getrow($sql);
        if ($rs) {

            $file_url        = $this->c['doc_host'] . date("Ymd", $rs['create_time']) . "/" . date("H", $rs['create_time']) . "/" . date("i", $rs['create_time']) . "/" . $rs['filename'];
            $doc             = $rs;
            $doc['file_url'] = $file_url;
            return $doc;
        } else {
            return false;
        }

    }

    // 获取商品库存
    public function getGoodsNumber($goods_id)
    {
        $goodsid = intval($goods_id);
        if ($goodsid > 0) {
            $sql = "SELECT `number` FROM {$this->_prefix['primary']}goods_stock WHERE `goods_id`=" . $goodsid;
            return $this->db->getone($sql);

        }
    }
    //上下架
    public function saveIsOnSale($da)
    {
        $code       = 900;
        $msg        = "修改失败";
        $goods_id   = intval($da['goods_id']);
        $is_on_sale = intval($da['is_on_sale']);

        $arr = array();
        if ($goods_id) {
            if ($is_on_sale) {

                $is_on_sale = 0;
            } else {
                $is_on_sale = 1;

            }

            $sql = "UPDATE {$this->_prefix['primary']}goods_data SET `is_on_sale`=" . $is_on_sale . ",`last_aid`=" . $this->_auth['aid'] . ",`last_edit`=" . date('ymd') . " WHERE `goods_id`=" . $goods_id;
            $res = $this->sql($sql);
            if ($res) {
                $code              = 200;
                $arr['is_on_sale'] = $is_on_sale;
                $msg               = "修改成功";
            }
        } else {
            $code = 901;
        }
        $arr['code'] = $code;
        $arr['msg']  = $msg;
        return $arr;
    }

    //修改零售价
    public function saveShopPrice($da)
    {

        $code       = 900;
        $msg        = "修改失败";
        $goods_id   = intval($da['goods_id']);
        $shop_price = number_format($da['shop_price'], 2, ".", "");
        $goods      = $this->getSingleGoods($goods_id);

        if ($shop_price < $goods['purchase_price']) {
            $arr['code'] = 902;
            $arr['msg']  = "售价不能小于进货价";

            return $arr;

        }
        $arr = array();
        if ($goods_id && $shop_price > 0 && $goods) {

            $sql = "UPDATE {$this->_prefix['primary']}goods_data SET `shop_price`=" . $shop_price . ",`last_aid`=" . $this->_auth['aid'] . ",`last_edit`=" . date('ymd') . " WHERE `goods_id`=" . $goods_id;
            $res = $this->sql($sql);
            if ($res) {
                $code = 200;
                $msg  = "修改成功";
            }
        } else {
            $code = 901;
        }
        $arr['code'] = $code;
        $arr['msg']  = $msg;
        return $arr;
    }

    //修改市场价
    public function saveMarketPrice($da)
    {

        $code         = 900;
        $msg          = "修改失败";
        $goods_id     = intval($da['goods_id']);
        $market_price = number_format($da['market_price'], 2, ".", "");
        $goods        = $this->getSingleGoods($goods_id);

        if ($market_price < $goods['shop_price']) {
            $arr['code'] = 902;
            $arr['msg']  = "市场价不能小于售价";

            return $arr;

        }
        $arr = array();
        if ($goods_id && $market_price && $goods) {

            $sql = "UPDATE {$this->_prefix['primary']}goods_data SET `market_price`=" . $market_price . ",`last_aid`=" . $this->_auth['aid'] . ",`last_edit`=" . date('ymd') . " WHERE `goods_id`=" . $goods_id;
            $res = $this->sql($sql);
            if ($res) {
                $code = 200;
                $msg  = "修改成功";
            }
        } else {
            $code = 901;
        }
        $arr['code'] = $code;
        $arr['msg']  = $msg;
        return $arr;
    }
    //增加商品库存
    public function saveGoodsNumber($data, $type = true)
    {

        $code = 900;

        $goods_id      = intval($data['goods_id']);
        $change_number = intval($data['goods_number']);
        if ($change_number > 0) {
            $number = 0;
            $this->db->begin();
            $commit = false;
            $code   = 403;
            if ($type) {
                $sql = "SELECT `number` FROM {$this->_prefix['primary']}goods_stock WHERE `goods_id`=" . $goods_id;
                $arr = $this->db->getrow($sql);
                if ($arr) {

                    $number = $arr['number'];
                    $sql    = "UPDATE {$this->_prefix['primary']}goods_stock SET `number`=`number`+" . $change_number . ",`last_aid`=" . $this->_auth['aid'] . ",`last_edit`=" . date('ymd') . " WHERE `goods_id`=" . $goods_id;

                } else {

                    $sql = "INSERT INTO {$this->_prefix['primary']}goods_stock (`goods_id`,`number`,`last_aid`,`last_edit`) VALUES (" . $goods_id . "," . $change_number . "," . $this->_auth['aid'] . "," . date('ymd') . ")";

                }

            } else {
                $sql = "UPDATE {$this->_prefix['primary']}goods_stock SET `number`=" . $change_number . ",`last_aid`=" . $this->_auth['aid'] . ",`last_edit`=" . date('ymd') . " WHERE `goods_id`=" . $goods_id;

            }
            $res = $this->sql($sql);
            if ($res > 0) {
                // 保存记录
                $sql = "INSERT INTO {$this->_prefix['primary']}goods_stock_log (`goods_id`,`type`,`goods_number`,`change_number`,`create_time`,`aid`) VALUES (" . $goods_id . ",1," . $number . "," . $change_number . "," . $_SERVER['REQUEST_TIME'] . "," . $this->_auth['aid'] . ")";

                $rcs = $this->sql($sql);
                if ($rcs > 0) {
                    $commit = true;
                }
            }

            if ($commit) {
                $this->db->commit();
                $code = 200;
            } else {
                $this->db->rollback();
            }

        }

        return $code;

    }

    //保存报损数据
    public function saveGoodsDamaged($da)
    {

        $code = 900;

        $goods_id      = intval($da['goods_id']);
        $change_number = intval($da['goods_number']);
        if ($change_number > 0) {
            $sql  = "SELECT `number` FROM {$this->_prefix['primary']}goods_stock WHERE `goods_id`=" . $goods_id;
            $data = $this->db->getrow($sql);

            if ($data) {
                if ($data['number'] >= $change_number) {
                    $this->db->begin();
                    $commit = false;
                    $code   = 403;

                    $sql = "UPDATE {$this->_prefix['primary']}goods_stock SET `number`=`number`-" . $change_number . " WHERE `goods_id`=" . $goods_id;

                    $res = $this->sql($sql);
                    if ($res > 0) {
                        // 保存记录
                        $sql = "INSERT INTO {$this->_prefix['primary']}goods_stock_log (`goods_id`,`type`,`goods_number`,`change_number`,`create_time`,`aid`,`note`) VALUES (" . $goods_id . ",2," . $data['number'] . "," . $change_number . "," . $_SERVER['REQUEST_TIME'] . "," . $this->_auth['aid'] . ",'" . addslashes(htmlspecialchars(trim($da['note']))) . "')";

                        $rcs = $this->sql($sql);
                        if ($rcs > 0) {
                            $commit = true;
                        }
                    }

                    if ($commit) {
                        $this->db->commit();
                        $code = 200;
                    } else {
                        $this->db->rollback();
                    }

                } else {
                    $code = 680;
                }

            } else {
                $code = 404;
            }

        }

        return $code;

    }

    // 获取走势数据
    public function getChartData($goods_id, $get_start_time = 0, $get_end_time = 0)
    {
        if ($get_start_time > 0) {
            $tsql .= " AND `create_time`>=" . $get_start_time;
            $start_time = $get_start_time;
        } else {
            $get_start_time = $start_time = strtotime(date("Y-m-1 0:0:0"));
            $tsql .= " AND `create_time`>=" . $get_start_time;
        }
        if ($get_end_time > 0) {
            $tsql .= " AND `create_time`<=" . $get_end_time;
        }

        $sql = "SELECT `change_number`,`create_time`,`type` FROM {$this->_prefix['primary']}goods_stock_log WHERE `goods_id`=" . $goods_id . $tsql;

        $data = $this->sql($sql);

        if ($data) {
            if ($get_start_time > 0) {
                $start_time = $get_start_time;
            } else {
                $start_time = $_SERVER['REQUEST_TIME'];
            }

            $end_time = $get_end_time;

            foreach ($data as $r) {
                if ($r['create_time'] < $start_time) {
                    $start_time = $r['create_time'];
                }

                if ($r['create_time'] > $end_time) {
                    $end_time = $r['create_time'];
                }

                $new[$r['type']][date("m-d", $r['create_time'])] += $r['change_number'];
            }

        }

        if ($get_start_time > 0) {
            $rsql .= " AND `add_time`>=" . $get_start_time;
        }

        if ($get_end_time > 0) {
            $rsql .= " AND `add_time`<=" . $get_end_time;
        }

        // 获取销售数据
        $sql = "SELECT `goods_number`,`add_time` FROM {$this->_prefix['primary']}order_goods WHERE `goods_id`=" . $goods_id . $rsql;
        // echo $sql;
        $sale = $this->sql($sql);

        if ($sale) {
            foreach ($sale as $r) {
                if ($r['add_time'] < $start_time) {
                    $start_time = $r['add_time'];
                }

                if ($r['add_time'] > $end_time) {
                    $end_time = $r['add_time'];
                }

                $new[3][date("m-d", $r['add_time'])] += $r['goods_number'];
            }
        }

        $start_time_str = date("Y-m-d", $start_time);
        $end_time_str   = date("Y-m-d", $end_time);

        while ($start_time < $end_time) {

            $dt = date("m-d", $start_time);

            $date[$dt] = $dt;
            $start_time += 86400;

        }
        $dt        = date("m-d", $end_time);
        $date[$dt] = $dt;

        return array(
            'start' => $start_time_str,
            'end'   => $end_time_str,
            'date'  => $date,
            'data'  => $new,
        );

    }

    //获取省份信息
    public function getprovince()
    {
        $sql      = "SELECT region_id,region_name FROM {$this->_prefix['primary']}region WHERE `parent_id`=0";
        $province = $this->sql($sql);
        return $province;
    }

    public function getposition($region_id)
    {
        $code = 404;
        if ($region_id > 0) {
            $sql      = "SELECT region_id,region_name FROM {$this->_prefix['primary']}region WHERE `parent_id`=" . $region_id;
            $position = $this->sql($sql);
            if ($position) {
                $code = 200;
            }
        }
        return array('code' => $code, 'data' => $position);
    }

    //保存商品区域地址
    public function saveRegion($data)
    {
        $code = 900;
        if ($data) {
            $goods_id = intval($data['goods_id']);
            $sql      = "SELECT * FROM {$this->_prefix['primary']}goods_region WHERE `goods_id`=" . $goods_id;
            $res      = $this->sql($sql);
            if ($res) {
                $sql = "DELETE FROM {$this->_prefix['primary']}goods_region WHERE   `goods_id`=" . $goods_id;
                $arr = $this->sql($sql);
                //echo $arr;die;
                if ($arr) {
                    $sql = "INSERT INTO {$this->_prefix['primary']}goods_region (`shopid`,`goods_id`,`region_id`) VALUES ";
                    foreach ($data['second'] as $v) {
                        $tsql[] = "(" . $this->_auth['shopid'] . "," . $goods_id . "," . $v . ")";
                    }
                    if ($tsql) {
                        $str = implode(',', $tsql);
                        if ($str) {
                            $sql .= $str;

                            $rs = $this->sql($sql);
                            if ($rs) {
                                $code = 200;
                            } else {
                                $code = 403;
                            }
                        }

                    }
                }
            } else {
                $sql = "INSERT INTO {$this->_prefix['primary']}goods_region (`shopid`,`goods_id`,`region_id`) VALUES ";
                foreach ($data['second'] as $v) {
                    $tsql[] = "(" . $this->_auth['shopid'] . "," . $goods_id . "," . $v . ")";
                }
                if ($tsql) {
                    $str = implode(',', $tsql);
                    if ($str) {
                        $sql .= $str;

                        $rs = $this->sql($sql);
                        if ($rs) {
                            $code = 200;
                        } else {
                            $code = 403;
                        }
                    }

                }

            }
        }
        return $code;
    }

    //查询已经存在的商品地址
    public function getGoodsRegion($goodsid)
    {
        $sql = "SELECT region_id FROM {$this->_prefix['primary']}goods_region WHERE `goods_id`=" . $goodsid;
        $arr = $this->sql($sql);
        if ($arr) {
            foreach ($arr as $v) {
                $regionids[] = $v['region_id'];
            }
            if ($regionids) {
                $regionid_str = implode(',', $regionids);
                if ($regionid_str) {
                    $sql = "SELECT region_id,region_name FROM {$this->_prefix['primary']}region WHERE `region_id` IN ($regionid_str)";
                    $res = $this->sql($sql);
                }
            }
        }
        return $res;
    }

    //获取供应商发货信息
    public function getSupplier($supplierid = 0)
    {
        if ($supplierid > 0) {$tsql = " AND `supplierid` = " . $supplierid;}
        $sql = "SELECT * FROM {$this->_prefix['primary']}shop_supplier WHERE `stat` =1 " . $tsql . " ORDER BY `supplierid` DESC";
        if ($supplierid > 0) {
            $data = $this->db->getrow($sql);
        } else {
            $data = $this->sql($sql);
        }

        return $data;
    }

    //获取供应商发货信息
    public function getSuppliers($supplierid = 0)
    {
        if ($supplierid > 0) {$tsql = " AND `id` = " . $supplierid;}
        $sql = "SELECT * FROM {$this->_prefix['primary']}supplier WHERE `statu` =1 " . $tsql . " ORDER BY `id` DESC";
        if ($supplierid > 0) {
            $data = $this->db->getrow($sql);
        } else {
            $data = $this->sql($sql);
        }

        return $data;
    }

    //getGoodsComment获取评论
    public function getGoodsComment($para, $page = 1, $pagesize = 10)
    {

        $where = "";
        if ($para) {

            if ($para['keyword'] != '') {
                $where .= " AND GD.`goods_name` LIKE '%" . $para['keyword'] . "%'";
            }

            if ($para['stat'] != '') {
                $where .= " AND GC.`stat` =" . $para['stat'];
            }

        }

        $sql = "SELECT COUNT(`id`) AS `cnt` FROM {$this->_prefix['primary']}order_goods_comment AS GC WHERE " . $where;

        $cnt = $this->db->getone($sql);
        if ($cnt > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "GC.`last_staffedit` DESC,GC.`id` DESC";

            $file = "GC.`id`,GC.`lev`,GC.`stat`,GC.`note`,GC.`last_staffedit`,GD.`goods_name`,MW.`nickname`";
            $sql  = "SELECT " . $file . " FROM {$this->_prefix['primary']}order_goods_comment AS GC";
            $sql .= "  LEFT JOIN {$this->_prefix['primary']}member_wechat AS MW ON MW.uid = GC.uid";
            $sql .= " LEFT JOIN {$this->_prefix['primary']}goods_data AS GD ON GD.goods_id = GC.goods_id";

            $sql .= "  WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;

            $rs = $this->sql($sql);
        }

        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt / $pagesize),
            'count'   => $cnt,
            'data'    => $rs,
            'para'    => $para,
        );
    }

    //saveCommentStat审核评论
    public function saveCommentStat($da)
    {
        $code = 403;
        $id   = intval($da['id']);
        if ($id > 0) {
            $sql  = "SELECT * FROM {$this->_prefix['primary']}order_goods_comment WHERE `id` =" . $id;
            $data = $this->db->getrow($sql);
            if ($data) {
                $stat = $data['stat'] > 1 ? 1 : 2;
                $sql  = "UPDATE {$this->_prefix['primary']}order_goods_comment SET `stat` =" . $stat . " WHERE `id`=" . $id;
                $b    = $this->sql($sql);
                if ($b) {
                    $code = 200;
                    $msg  = $stat;
                }
            }
        }
        return array('code' => $code, 'msg' => $msg);
    }

    //删除分类
    public function deleteCategory($caid)
    {
        $sql = "DELETE FROM {$this->_prefix['primary']}goods_category WHERE `caid`=" . intval($caid) . "   LIMIT 1";
        return $this->sql($sql);
    }

    //删除品牌
    public function deleteBrand($brand_id)
    {
        $sql = "DELETE FROM {$this->_prefix['primary']}brand WHERE `brand_id`=" . intval($brand_id) . "   LIMIT 1";
        return $this->sql($sql);
    }

    //获取所有类别
    public function getClasslist($caid = 0, $isfucaid = false)
    {
        if ($isfucaid) {
            $tsql = " AND `fucaid`=" . intval($caid);
        } elseif ($caid > 0) {
            $tsql = " AND `caid`=" . intval($caid);
        }

        $sql = "SELECT * FROM {$this->_prefix['primary']}brand_category WHERE  `stat`<3" . $tsql . " ORDER BY `stat` ASC ,`sort` ASC";

        if ($caid > 0 && !$isfucaid) {
            $newdata = $this->db->getrow($sql);
        } else {
            $data = $this->sql($sql);
            if ($data) {
                if ($isfucaid) {
                    $newdata = $data;
                } else {
                    foreach ($data as $r) {
                        $newdata[$r['fucaid']][$r['caid']] = $r;
                    }
                }
            }
        }
        return $newdata;
    }

    //保存品牌分类
    public function saveClass($da, $file, $caid = 0)
    {

        $code   = 900;
        $name   = addslashes(htmlspecialchars(trim($da['name'])));
        $names  = addslashes(htmlspecialchars(trim($da['names'])));
        $stat   = intval($da['stat']);
        $fucaid = intval($da['fucaid']);
        //分类logo处理
        if ($file['pic_big']['tmp_name'] != "" && $file['pic_big']['size'] > 0) {
            $savegoods = false;
            if (in_array($file['pic_big']['type'], $this->c['upload']['mime'])) {

                if ($file['pic_big']['size'] <= $this->c['upload']['size']) {
                    $format = $this->upload->rf($file['pic_big']['name']);

                    if (in_array($format, $this->c['upload']['fm'])) {

                        //创建目录
                        $dir['date'] = $this->c['upload']['dir'] . date("Ymd", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['date'])) {
                            mkdir($dir['date']);
                        }

                        $dir['hour'] = $dir['date'] . DIRECTORY_SEPARATOR . date("H", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['hour'])) {
                            mkdir($dir['hour']);
                        }

                        $dir['minute'] = $dir['hour'] . DIRECTORY_SEPARATOR . date("i", $_SERVER['REQUEST_TIME']);
                        if (!file_exists($dir['minute'])) {
                            mkdir($dir['minute']);
                        }

                        if (file_exists($dir['minute'])) {

                            //移动文件
                            $filename = md5($file['pic_big']['tmp_name'] . $_SERVER['REQUEST_TIME']) . "." . $format;
                            $filepath = $dir['minute'] . DIRECTORY_SEPARATOR . $filename;

                            if (move_uploaded_file($file['pic_big']['tmp_name'], $filepath)) {
                                $docid = $this->saveDocument($file['pic_big']['name'], $filename, $file['pic_big']['size'], $format, $_SERVER['REQUEST_TIME']);
                                if ($docid > 0) {
                                    $field['pic_docid']  = $docid;
                                    $pic_big['filepath'] = $filepath;
                                    $pic_big['name']     = $file['pic_big']['name'];
                                    $pic_big['format']   = $format;
                                    $savegoods           = true;
                                } else {
                                    $code = 701;
                                    @unlink($filepath);
                                }
                            } else {
                                $code = 705;
                            }

                        } else {
                            $code = 706;
                        }

                    } else {
                        $code = 703;
                    }

                } else {
                    $code = 704;
                }

            } else {
                $code = 703;
            }

        }
        //修改
        if ($caid > 0) {
            $sql = "SELECT * FROM {$this->_prefix['primary']}brand_category WHERE `caid`=" . intval($caid) . "  AND `stat`<3";
            $rs  = $this->db->getrow($sql);

            if ($rs) {
                if ($docid) {
                    $s = ',`docid`=' . $docid . '';
                } else {
                    $s = '';
                }
                $sql = "UPDATE {$this->_prefix['primary']}brand_category SET `stat`=" . $stat . ",`fucaid`=" . $fucaid . ",`name`='" . $name . "',`names`='" . $names . "',`last_staffedit`=" . $_SERVER['REQUEST_TIME'] . $s . " WHERE `caid`=" . $rs['caid'];
                $rd  = $this->sql($sql);
                if ($rd > 0) {
                    $code = 200;
                } else {
                    $code = 403;
                }

            } else {
                $code = 404;
            }
        }
        //新增
        else {
            if ($da['name'] != "") {

                $sql = "INSERT INTO {$this->_prefix['primary']}brand_category
                    (`name`,`names`,`fucaid`,`stat`,`last_staffedit`,`docid`) VALUES
                    ('" . $name . "','" . $names . "'," . $fucaid . "," . $stat . "," . $_SERVER['REQUEST_TIME'] . "," . $docid . ")";

                $rd = $this->sql($sql);

                if ($rd > 0) {
                    $code = 200;
                } else {
                    $code = 403;
                }

            }
        }
        return $code;

    }

    //供应商信息列表
    public function getSupplierlist($para, $page = 1, $pagesize = 15)
    {

        if ($para) {
            if ($para['keyword'] != '') {
                $where .= " AND `supplier` LIKE '%" . $para['keyword'] . "%' ";
            }
        }

        $sql = "SELECT COUNT(`id`) AS `cnt` FROM {$this->_prefix['primary']}supplier" . $where;
        $cnt = $this->db->getone($sql);
        if ($cnt > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "`id` DESC";

            $sql = "SELECT * FROM {$this->_prefix['primary']}supplier  ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;

            $rs = $this->sql($sql);

        }
        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt / $pagesize),
            'count'   => $cnt,
            'data'    => $rs,
            'para'    => $para,
        );
    }

    public function getRegion($parent_id)
    {
        $sql  = "SELECT `region_id`,`region_name` FROM {$this->_prefix['primary']}region WHERE `parent_id`=" . $parent_id . " ORDER BY `region_id` ASC";
        $data = $this->sql($sql);
        return $data;
    }
    //获取单个供应商
    public function getSingleSupplier($id)
    {
        $sql  = "SELECT * FROM {$this->_prefix['primary']}supplier WHERE `id`=" . intval($id) . "  LIMIT 1";
        $data = $this->db->getrow($sql);
        return $data;
    }

    //验证供应商手机号是否存在
    public function searchPhone($da)
    {
        $phone = $da['phone'];
        $sql   = "SELECT * FROM {$this->_prefix['primary']}supplier WHERE  `statu`<3 and `phone` =" . $phone;
        $data  = $this->sql($sql);
        if ($data) {
            $code = 200;
        }
        return $code;
    }
    //保存供应商信息
    public function saveSupplier($da, $file, $id = 0)
    {
        $code                     = 900;
        $saveSupplier             = true; //执行供应商信息保存的标记
        $field['supplier']        = addslashes(htmlspecialchars(trim($da['supplier']))); //供应商名称
        $field['address']         = addslashes(htmlspecialchars(trim($da['address']))); //供应商地址
        $field['mailbox']         = addslashes(htmlspecialchars(trim($da['mailbox']))); //负责人邮箱
        $field['finance_name']    = addslashes(htmlspecialchars(trim($da['finance_name']))); //财务姓名
        $field['finance_phone']   = addslashes(htmlspecialchars(trim($da['finance_phone']))); //财务电话
        $field['finance_email']   = addslashes(htmlspecialchars(trim($da['finance_email']))); //财务邮箱
        $field['company_name']    = addslashes(htmlspecialchars(trim($da['company_name']))); //公司名称
        $field['tel']             = addslashes(htmlspecialchars(trim($da['tel']))); //座机
        $field['realname']        = addslashes(htmlspecialchars(trim($da['suppliername']))); //负责人姓名
        $field['phone']           = addslashes(htmlspecialchars(trim($da['phone']))); //负责人联系电话
        $field['payment_account'] = addslashes(htmlspecialchars(trim($da['payment_account']))); //负责人联系电话
        //保存供应商信息
        if ($field['supplier'] != "" && $saveSupplier) {
            $code = 403;
            //开始事务
            $this->db->begin();
            $rollback = true;
            //print_r($file);die;
            //商品大图1处理
            if ($file['headimgurl']['tmp_name'] != "" && $file['headimgurl']['size'] > 0) {

                $savegoods = false;
                if (in_array($file['headimgurl']['type'], $this->c['upload']['mime'])) {

                    if ($file['headimgurl']['size'] <= $this->c['upload']['size']) {
                        $format = $this->upload->rf($file['headimgurl']['name']);

                        if (in_array($format, $this->c['upload']['fm'])) {

                            //创建目录
                            $dir['date'] = $this->c['upload']['dir'] . date("Ymd", $_SERVER['REQUEST_TIME']);
                            if (!file_exists($dir['date'])) {
                                mkdir($dir['date']);
                            }

                            $dir['hour'] = $dir['date'] . DIRECTORY_SEPARATOR . date("H", $_SERVER['REQUEST_TIME']);
                            if (!file_exists($dir['hour'])) {
                                mkdir($dir['hour']);
                            }

                            $dir['minute'] = $dir['hour'] . DIRECTORY_SEPARATOR . date("i", $_SERVER['REQUEST_TIME']);
                            if (!file_exists($dir['minute'])) {
                                mkdir($dir['minute']);
                            }

                            if (file_exists($dir['minute'])) {

                                //移动文件$this->c['doc_host']
                                $filename = md5($file['headimgurl']['tmp_name'] . $_SERVER['REQUEST_TIME']) . "." . $format;
                                $filepath = $dir['minute'] . DIRECTORY_SEPARATOR . $filename;

                                $url = date("Ymd", $_SERVER['REQUEST_TIME']) . "/" . date("H", $_SERVER['REQUEST_TIME']) . "/" . date("i", $_SERVER['REQUEST_TIME']) . "/" . $filename;
                                //$url_thumb = date("Ymd", $time) . "/" . date("H", $time) . "/" . date("i", $time) . "/" . $thumb_filename;

                                $path = $this->c['doc_host'] . $url;

                                if (move_uploaded_file($file['headimgurl']['tmp_name'], $filepath)) {

                                    // 压缩图片
                                    $this->upload->mt($filepath, $filepath, 2000, 5000, 90);
                                    $tmpfilesize = filesize($filepath);
                                    //$docid       = $this->saveDocument($file['headimgurl']['name'], $filename, $tmpfilesize, $format, $_SERVER['REQUEST_TIME']);
                                    $field['headimgurl'] = $path;
                                    /*if ($docid > 0) {

                                $pic_big['filepath'] = $filepath;
                                $savegoods = true;
                                } else {
                                $code = 701;
                                @unlink($filepath);
                                }*/
                                } else {
                                    $code = 705;
                                }

                            } else {
                                $code = 706;
                            }

                        } else {
                            $code = 703;
                        }

                    } else {
                        $code = 704;
                    }

                } else {
                    $code = 703;
                }

                @unlink($file['headimgurl']['tmp_name']);
            }
            //修改
            if ($id > 0) {
                $supplier = $this->getSingleSupplier($id);

                if ($supplier) {
                    //修改供应商信息
                    $sql = "UPDATE {$this->_prefix['primary']}supplier SET ";
                    foreach ($field as $key => $value) {
                        $upsql[] = "`" . $key . "`='" . $value . "'";
                    }
                    $sql .= implode(",", $upsql) . " WHERE `id`=" . $supplier['id'];
                    $rcnum = $this->sql($sql);
                    if ($rcnum) {
                        $code = 200;
                        $this->db->commit();
                        $rollback = false;
                    }
                } else {
                    $code = 404;
                }

            }
            //新增
            else {
                foreach ($field as $key => $value) {
                    $keys[]   = "`" . $key . "`";
                    $values[] = "'" . $value . "'";
                }
                //按商铺添加供应商编号 yxs 2017.09.01
                $supplier_no = $this->db->getone("SELECT count(*) FROM {$this->_prefix['primary']}supplier ");
                if ($supplier_no <= 0) {
                    $supplier_no = 1;
                } else {
                    $supplier_no += 1;
                }

                //插入供应商信息
                $sql = "INSERT INTO {$this->_prefix['primary']}supplier (" . implode(",", $keys) . ") VALUES (" . implode(",", $values) . ")";
                $id  = $this->sql($sql);
                if ($id > 0) {
                    $done = true;
                    if ($done) {
                        $code = 200;
                        $this->db->commit();
                        $rollback = false;
                    }
                }

            } //end of add
            if ($rollback) {
                $this->db->rollback();
            }

        }

        return $code;
    }
    //删除供应商信息
    public function del_supplier($ids, $act)
    {
        if ($act == "delete") {
            $sql = "DELETE  FROM {$this->_prefix['primary']}supplier  WHERE `id` =" . $ids;
            $rc  = $this->sql($sql);
        } elseif ($act == "delAll") {
            $ids = explode(",", $ids);
            foreach ($ids as $v) {
                $sql = "DELETE  FROM {$this->_prefix['primary']}supplier  WHERE `id` =" . $v;
                $rc  = $this->sql($sql);
            }
        }
        if ($rc > 0) {
            $code = 200;
        } else {
            $code = 403;
        }

        return $code;
    }

    //渠道商品导出
    public function getDerive($para)
    {
        $where = " `is_delete`=0";

        if ($para['caid'] != '') {

            $cate = $this->getCategory($para['caid']);

            if ($cate['fucaid'] > 0) {
                $where .= " AND `caid`=" . $para['caid'];
            } else {

                $cateId[] = $para['caid'];

                $cates = $this->getCategory($para['caid'], true);
                if ($cates) {
                    foreach ($cates as $val) {
                        $cateId[] = $val['caid'];

                    }
                }

                $where .= " AND `caid` IN (" . implode(",", $cateId) . ")";
            }

        }

        if ($para['brand_id'] != '') {
            $where .= " AND `brand_id`=" . $para['brand_id'];
        }

        if ($para['goods_name'] != '') {
            $where .= " AND `goods_name` LIKE '%" . $para['goods_name'] . "%'";
        }

        if (isset($para['is_on_sale'])) {

            $where .= " AND `is_on_sale`=" . $para['is_on_sale'];
        }

        $sql = "SELECT `goods_id`,`caid`,`goods_name`,`brand_id`,`market_price`,`shop_price`,`supply_price`,`purchase_price`,`tmall_price`,`is_on_sale` FROM {$this->_prefix['primary']}goods_data  WHERE " . $where . " ORDER BY `add_time` DESC,`goods_id` DESC ";

        $data = $this->sql($sql);
        //print_r($data);die;
        if ($data) {
            foreach ($data as $key => $value) {
                $caids = $this->getCategory($value['caid']);

                $data[$key]['caid'] = $caids['name']; //分类名字

                $brand_ids              = $this->getBrand($value['brand_id']);
                $data[$key]['brand_id'] = $brand_ids['name']; //品牌名字

                //库存
                $sql                        = "SELECT `number` FROM {$this->_prefix['primary']}goods_stock WHERE `goods_id`=" . $value['goods_id'];
                $goods_stock                = $this->db->getrow($sql);
                $data[$key]['goods_number'] = $goods_stock['number'];
                //上下架
                if ($value['is_on_sale']) {
                    $data[$key]['is_on_sale'] = "是";
                } else {
                    $data[$key]['is_on_sale'] = "否";

                }
            }
        }
        return $data;

    }

    // 导入渠道商品信息
    public function saveImport($da)
    {
        $code = 404;

        if (is_array($da)) {

            $this->db->begin();
            $commit = false;
            $code   = 403;
            foreach ($da as $r) {
                if ($r[0] != "" && $r[5] != "") {

                    $goods_id         = intval($r[0]);
                    $shop_price       = number_format($r[5], 2, '.', '');
                    $market_price     = number_format($r[6], 2, '.', '');
                    $purchase_price   = number_format($r[7], 2, '.', '');
                    $tmall_price      = number_format($r[8], 2, '.', '');
                    $supply_price     = number_format($r[9], 2, '.', '');
                    $discount_percent = number_format($shop_price / $market_price, 2, '.', '');

                    $sql = "UPDATE {$this->_prefix['primary']}goods_data SET `shop_price`='" . $shop_price . "',`market_price`='" . $market_price . "',`purchase_price`='" . $purchase_price . "',`tmall_price`='" . $tmall_price . "',`supply_price`='" . $supply_price . "',`discount_percent`='" . $discount_percent . "' WHERE `goods_id`=" . $goods_id;
                    $rcs = $this->sql($sql);

                    if ($rcs) {
                        $this->db->commit();
                        $code = 200;
                    } else {
                        $this->db->rollback();
                    }

                }
            }
        }
        return $code;

    }

    // 获取商品的关联信息
    public function getGoodsRelevance($goods_id)
    {
        $code = 404;

        $sql   = "SELECT `goods_id`,`goods_name`,`relevance_id`,`rele_title` FROM {$this->_prefix['primary']}goods_data WHERE `goods_id`=" . intval($goods_id) . " AND `is_delete`=0 LIMIT 1";
        $goods = $this->db->getrow($sql);
        if ($goods) {
            $code = 200;
            if ($goods['relevance_id'] > 0) {
                $sql                      = "SELECT `title` FROM {$this->_prefix['primary']}goods_relevance WHERE `id`=" . $goods['relevance_id'];
                $goods['relevance_title'] = $this->db->getone($sql);
            }
        }

        return array(
            'code' => $code,
            'data' => $goods,
        );
    }

    // 保存商品列表的关联操作
    public function saveGoodsRlevances($da)
    {
        $code = 900;

        $goods_id = intval($da['goods_id']);

        if ($goods_id > 0) {
            $rele_title = addslashes(htmlspecialchars(trim($da['rele_title'])));
            if ($da['slk_relevance_id'] == "CANCEL") {
                $slk_relevance_id = 0;
            } elseif ($da['slk_relevance_id'] != "") {
                $slk_relevance_id = intval($da['slk_relevance_id']);
            } else {
                $slk_relevance_id = -1;
            }

            $sql   = "SELECT `goods_id`,`rele_title`,`relevance_id` FROM {$this->_prefix['primary']}goods_data WHERE `goods_id`=" . $goods_id;
            $goods = $this->db->getrow($sql);
            if ($goods) {
                $old_relevance_id = $goods['relevance_id'];

                if ($slk_relevance_id == -1) {
                    $sql = "UPDATE {$this->_prefix['primary']}goods_data SET `rele_title`='" . $rele_title . "' WHERE `goods_id`=" . $goods['goods_id'];
                    $rcs = $this->sql($sql);
                    if ($rcs > 0) {
                        $code = 200;
                    } else {
                        $code = 403;
                    }
                } elseif ($slk_relevance_id == 0) {
                    $this->db->begin();
                    $code   = 403;
                    $commit = false;

                    $sql = "UPDATE {$this->_prefix['primary']}goods_data SET `rele_title`='" . $rele_title . "',`relevance_id`=0 WHERE `goods_id`=" . $goods['goods_id'];
                    $rcs = $this->sql($sql);
                    if ($rcs > 0) {
                        $code   = 200;
                        $commit = true;

                        // 更新原来关联的数据ID
                        if ($old_relevance_id > 0) {
                            $commit = false;
                            $sql    = "SELECT `goods_id` FROM {$this->_prefix['primary']}goods_data WHERE `relevance_id`=" . $old_relevance_id;
                            $tmp    = $this->sql($sql);
                            if ($tmp) {
                                foreach ($tmp as $r) {
                                    $goods_ids_tmp[] = $r['goods_id'];
                                }

                                $goods_ids = implode(",", $goods_ids_tmp);
                            } else {
                                $goods_ids = '';
                            }

                            $sql = "UPDATE {$this->_prefix['primary']}goods_relevance SET `goods_ids`='" . $goods_ids . "' WHERE `id`=" . $old_relevance_id;
                            $rcs = $this->sql($sql);
                            if ($rcs > 0) {
                                $commit = true;
                            }
                        }
                    }

                    if ($commit) {
                        $this->db->commit();
                    } else {
                        $this->db->rollback();
                    }
                } elseif ($slk_relevance_id > 0) {
                    $this->db->begin();
                    $code   = 403;
                    $commit = false;

                    $sql = "UPDATE {$this->_prefix['primary']}goods_data SET `rele_title`='" . $rele_title . "',`relevance_id`=" . $slk_relevance_id . " WHERE `goods_id`=" . $goods['goods_id'];
                    $rcs = $this->sql($sql);
                    if ($rcs > 0) {
                        $code   = 200;
                        $commit = true;

                        // 更新原来关联的数据ID
                        if ($old_relevance_id > 0 && $old_relevance_id != $slk_relevance_id) {
                            $commit = false;
                            $sql    = "SELECT `goods_id` FROM {$this->_prefix['primary']}goods_data WHERE `relevance_id`=" . $old_relevance_id;
                            $tmp    = $this->sql($sql);
                            if ($tmp) {
                                foreach ($tmp as $r) {
                                    $goods_ids_tmp[] = $r['goods_id'];
                                }

                                $goods_ids = implode(",", $goods_ids_tmp);
                            } else {
                                $goods_ids = '';
                            }

                            $sql = "UPDATE {$this->_prefix['primary']}goods_relevance SET `goods_ids`='" . $goods_ids . "' WHERE `id`=" . $old_relevance_id;
                            $rcs = $this->sql($sql);
                            if ($rcs > 0) {
                                $commit = true;
                            }
                        }

                        // 更新关联ID的商品ID集合
                        if ($commit) {
                            $commit = false;
                            $sql    = "SELECT `goods_id` FROM {$this->_prefix['primary']}goods_data WHERE `relevance_id`=" . $slk_relevance_id;
                            $tmp    = $this->sql($sql);
                            if ($tmp) {
                                foreach ($tmp as $r) {
                                    $goods_ids_tmp_slk[] = $r['goods_id'];
                                }

                                $goods_ids = implode(",", $goods_ids_tmp_slk);
                            } else {
                                $goods_ids = '';
                            }

                            $sql = "UPDATE {$this->_prefix['primary']}goods_relevance SET `goods_ids`='" . $goods_ids . "' WHERE `id`=" . $slk_relevance_id;
                            $rcs = $this->sql($sql);
                            if ($rcs > 0) {
                                $commit = true;
                            }
                        }

                    }

                    if ($commit) {
                        $this->db->commit();
                    } else {
                        $this->db->rollback();
                    }
                }
            } else {
                $code = 404;
            }
        }

        return array(
            'code' => $code,
        );

    }

    public function saveGoodsCate($da)
    {

        $goods_ids = trim($da['goods_ids']);
        $caid      = intval($da['caid']);
        if ($goods_ids && $caid) {
            $goods_ids = explode(',', $goods_ids);
            if (is_array($goods_ids)) {
                foreach ($goods_ids as $val) {

                    $sql = "UPDATE {$this->_prefix['primary']}goods_data SET `caid`=" . $caid . " WHERE goods_id=" . $val;
                    $rc  = $this->sql($sql);

                }
                $code = 200;
            }
            /*  $sql = "SELECT * FROM {$this->_prefix['primary']}goods_data WHERE `is_delete` =0 AND `goods_id` IN (".$goods_ids.")";
        $goodsList = $this->sql($sql); */

        }

        return $code;
    }

    // 获取设置
    public function getSetting()
    {
        $sql     = "SELECT `setting` FROM {$this->_prefix['primary']}setting ORDER BY `setting_id` DESC LIMIT 1";
        $setting = $this->db->getone($sql);
        if ($setting != "") {
            return json_decode($setting, true);
        }

    }

}
